简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM