Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

element.setAttribute('prop',value) vs element.prop = value

We have a setAttribute method, for DOM elements.

https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute

How is it different from using the below?

 domElement.propName = value

Is there any benefit to either approaches ?

Thanks.

like image 416
sbr Avatar asked Feb 19 '23 23:02

sbr


1 Answers

domElement.setAttribute('propName', obj) is setting an XML attribute, it will be converted into a string and added to the DOM tag.

domElement.propName is setting an expando property, it can be of any type. It's setting it on the JS object that wraps the DOM object implementation.

They do not have the same effect, unless you are dealing with an attribute that is recognized by the parser like src,id,value. Those properties get copied to the expando property but there are many rabbit holes and cases where it doesn't work reliably (usually when the expando doesn't take a string, like onclick, checked)

This example shows that they are different.

domElement.setAttribute('someProp', 5);
console.log(domElement.someProp); // undefined
domElement.someProp = 10; 
console.log(domElement.someProp); // 10
console.log(domElement.getAttribute('someProp')); // "5" -> it's a string 

Always using DOM expando properties is less likely to cause trouble. The only case where you want to use setAttribute is when you need to serialize the node (using outerHTML) and you want that attribute to be reflected in the serialization

like image 160
Juan Mendes Avatar answered Feb 21 '23 12:02

Juan Mendes