Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Interactive Web Pages with JavaScript Traversing and Manipulating the DOM with JavaScript Perform: Modifying Elements

John Barhorst
John Barhorst
9,648 Points

.className vs .setAttribute

I tend to learn a bit more if I try to work things out on my own and then come back to the video if I get stuck or to see how the teacher approached it.

In my working ahead on this portion, I ended up using .setAttribute("type", "text"); and .setAttribute("class", "edit"); ect. for my inputs.

For the actual text portions I used document.createTextNode(); which I can see is a bit sloppier than using the .inner methods. But for setting the class or input types on things, is there a "right" way to do that? Are there instances where .className or .setAttribute are more appropriate?

2 Answers

akak
akak
29,445 Points

.className is going to be a faster since it's not a method. The same with .innerText. I usually go for element.classList.add('class') as it allows to add multiple classes in one go and I can live with the fact that is a bit slower for that added bonus. setAttribute is useful when you need to... set an attribute that is not a style or class. But with one important note.

If you'd had an element with styles like this

.white-border
  border-color: white !important

setting its style like this would fail

element.style.borderColor = 'red';

That's the good use for .setAttribute as you can do

element.setAttribute('style', 'border-color: red !important');

And it would override the border color of the element.

John Barhorst
John Barhorst
9,648 Points

Right on, thanks for the reply. :D