Manuel
Manuel

Reputation: 2391

Can element attributes be accessed using a dot notation in Javascript?

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

Answers (1)

Satpal
Satpal

Reputation: 133433

You need to use className property to get and set the value of the class attribute of the specified element.

The name classNameis used for this property instead of class because of conflicts with the "class" keyword in many languages which are used to manipulate the DOM.

button.className= "foo"

Upvotes: 1

Related Questions