Reputation: 2391
I'm working on a script that dynamically creates a group of buttons, all of which are created with a class attribute so that I can style them. But the styling never worked.
I added the class value like so: button.class = "foo";
where button
is a reference to the <button>
element in the DOM.
I changed the above code to button.setAttribute("class", "foo");
and it works!
But this has me confused because I use the dot notation (or object property notation? I don't know what to call it) to set other values, like the attribute value
.
For example, I have an event listener on some buttons. When they're clicked, the value
attribute is added to the element. When it's clicked again, it's removed:
button.onclick = function() {
if (this.value)
this.removeAttribute("value");
else
this.value = "bar";
}
The above works as expected.
So my question is - why is it that notations like button.class = "foo";
seem to work with some attributes and not with others? And is there a way to find which attributes will behave appropriately using that notation?
Upvotes: 0
Views: 1100
Reputation: 133433
You need to use className
property to get and set the value of the class
attribute of the specified element.
The name
className
is used for this property instead ofclass
because of conflicts with the "class" keyword in many languages which are used to manipulate the DOM.
button.className= "foo"
Upvotes: 1