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 JavaScript and the DOM (Retiring) Traversing the DOM Sibling Traversal

Brandon Marrero
Brandon Marrero
5,532 Points

How to insert an attribute to an element?

I dont understand how to add an attribute, I used setAttribute() and setAttributeNode() and it still didnt work. Error said "undefined"

If you wouldn't mind being a little more specific, I may be able to help you further but here is what I know about setAttribute():

elementYouWantToModify.setAttribute('attributeName', 'attributeValue');

If you are getting undefined, then it may be because something is wrong with your element, not the method. Again I may be able to help you more if you are more specific

1 Answer

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 48,850 Points

Without seeing your code, I can only explain setAttribute.

setAttribute takes two arguments in the following order, attributeName and attributeValue.

e.g.

element.setAttribute("class", "highlight");