Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using createAttribute vs. just setting the attribute directly?

Tags:

People also ask

Can I create attribute in HTML?

HTML | DOM createAttribute() Method This createAttribute() method is used to create an attribute with the specified name and returns the attribute object. The attribute. value property is used to set the value of the attribute and the element. setAttribute() method is used to create a new attribute for an element.

Are HTML attributes always strings?

HTML attributes have the following features: Their name is case-insensitive ( id is same as ID ). Their values are always strings.

What method allows us to add an attribute to a DOM element?

The setAttribute() method sets a new value to an attribute.


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

By 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 by just setting the attributes directly:

var input = document.createElement("input");

input.type = "text";
container.appendChild(input);

The latter can end up being quite lot less code, even when there are only a couple attributes per element.

The question: has anyone run across any drawbacks of the latter method (setting attributes directly)?

I tested this on several browsers (the latest FF, IE, Safari, Opera, old IEs - even IE6 worked) and on a basic test (inserting a text input with type, name, and maxLength attributes) they all passed. Here's the fiddle if anybody needs it.