When to use setAttribute vs .attribute= in JavaScript? When to use setAttribute vs .attribute= in JavaScript? javascript javascript

When to use setAttribute vs .attribute= in JavaScript?


From Javascript: The Definitive Guide, it clarifies things. It notes that HTMLElement objects of a HTML doc define JS properties that correspond to all standard HTML attributes.

So you only need to use setAttribute for non-standard attributes.

Example:

node.className = 'test'; // worksnode.frameborder = '0'; // doesn't work - non standard attributenode.setAttribute('frameborder', '0'); // works


None of the previous answers are complete and most contain misinformation.

There are three ways of accessing the attributes of a DOM Element in JavaScript. All three work reliably in modern browsers as long as you understand how to utilize them.

1. element.attributes

Elements have a property attributes that returns a live NamedNodeMap of Attr objects. The indexes of this collection may be different among browsers. So, the order is not guaranteed. NamedNodeMap has methods for adding and removing attributes (getNamedItem and setNamedItem, respectively).

Notice that though XML is explicitly case sensitive, the DOM spec calls for string names to be normalized, so names passed to getNamedItem are effectively case insensitive.

Example Usage:

var div = document.getElementsByTagName('div')[0];//you can look up specific attributesvar classAttr = div.attributes.getNamedItem('CLASS');document.write('attributes.getNamedItem() Name: ' + classAttr.name + ' Value: ' + classAttr.value + '<br>');//you can enumerate all defined attributesfor(var i = 0; i < div.attributes.length; i++) {  var attr = div.attributes[i];  document.write('attributes[] Name: ' + attr.name + ' Value: ' + attr.value + '<br>');}//create custom attributevar customAttr = document.createAttribute('customTest');customAttr.value = '567';div.attributes.setNamedItem(customAttr);//retreive custom attributecustomAttr = div.attributes.getNamedItem('customTest');document.write('attributes.getNamedItem() Name: ' + customAttr.name + ' Value: ' + customAttr.value + '<br>');
<div class="class1" id="main" data-test="stuff" nonStandard="1234"></div>