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?
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() .
The setAttribute() method adds the specified attribute to an element, and gives it the specified value.
The setAttribute() method sets a new value to an attribute.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With