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.
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
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