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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
domElement.setAttribute('propName', obj)is setting an XML attribute, it will be converted into a string and added to the DOM tag.domElement.propNameis 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, likeonclick, checked)This example shows that they are different.
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