Using createAttribute or just setting an attribute directly?

In javascript, we can create a new DOM element in the following ways:

Using the createAttribute () + setAttributeNode () dom methods:

var input = document.createElement("input"), type = document.createAttribute("type"); type.nodeValue = "text"; input.setAttributeNode(type); container.appendChild(input); 

or just setting attributes directly:

 var input = document.createElement("input"); input.type = "text"; container.appendChild(input); 

The latter may turn out to be much less code, even if there are only a couple of attributes per element.

Question: Does anyone encounter any shortcomings of the latter method (setting attributes directly)?

I tested this on several browsers (the latest FF, IE, Safari, Opera, old IE - even IE6 worked) and on the basic test (inserting text input with the type, name and attributes of maxLength) that they all passed. Here is the violin , if anyone needs it.

+7
source share
2 answers
 document.createAttribute document.createAttributeNS element.getAttributeNode element.getAttributeNodeNS ... and a lot of others 

will be deprecated in DOM4, so do not use it, just set using setAttribute ("name", "value")

http://www.w3.org/TR/dom/#element

someinput.type differs basically it's a shortcut to execute

 setAttribute("type","text"); getAttribute("text"); 

hope this helps!

 element._some_attribute_ is not available for all attributes, just some: element.dir element.lang element.id ...etc 
+9
source

Obviously, IE 5.5 has problems using the attribute name (ie node[attributeName] ). Quirksmode is well documented .

+3
source

All Articles