Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.setAttribute('style', 'attribute :value;') vs. element.attribute = 'value'

Tags:

In javascript is there any difference between using

element.style.setAttribute('width', '150px'); 

and

element.style.width = '150px'; 

?

I have seen that keywords won't work with the first way (like this), but for non-keyword attributes is there a difference?

like image 959
rosscj2533 Avatar asked Dec 09 '09 18:12

rosscj2533


People also ask

How do you set an attribute and its value?

Element.setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .

Which method adds the specified attribute to an element in the specified value?

The setAttribute() method adds the specified attribute to an element, and gives it the specified value.

What method allows us to add an attribute to a DOM element?

The setAttribute() method sets a new value to an attribute.

What is the setAttribute method?

The setAttribute() method is used to set or add an attribute to a particular element and provides a value to it. If the attribute already exists, it only set or changes the value of the attribute. So, we can also use the setAttribute() method to update the existing attribute's value.


1 Answers

Both are perfectly valid. Can you give some examples which doesn't work in second way? Are you aware that attribute names needs to be camelcased first? E.g. element.style.marginTop instead of incorrectly element.style.margin-top. The hyphen is namely an invalid identifier in Javascript.

like image 137
BalusC Avatar answered Oct 03 '22 14:10

BalusC