9

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.

uɥƃnɐʌuop
  • 14,022
  • 5
  • 58
  • 61

2 Answers2

13
document.createAttribute
document.createAttributeNS
element.getAttributeNode
element.getAttributeNodeNS
... and a lot of others

will be deprecated in DOM4, so don't use it, just set with setAttribute("name","value")

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

someinput.type is different basically is a shortcut for doing

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
  • 2
    It's not entirely true that using `setAttribute()` and `getAttribute()` is always equivalent to using the corresponding property. For example, the `value` property (which always reflects the current value of an input) exists separately from the `value` attribute (which represents only the initial value). A more obvious example is the `style` attribute, which contains a string, versus the `style` property, which is a `CSSStyleDeclaration` object with individual properties for each individual style property. – Tim Down Oct 06 '11 at 22:58
  • where did i say that they're always equivalent? :P –  Jul 26 '13 at 11:57
  • Fair point, you didn't. Not sure what prompted my comment now. – Tim Down Jul 26 '13 at 13:24
  • @TimDown nonetheless, appreciate the indepth distinction – puiu Oct 05 '16 at 17:12
  • See you in a couple of years for my next comment :) – Tim Down Oct 06 '16 at 13:24
3

Apparantly IE 5.5 has issues with using the attribute name (i.e. node[attributeName]). Quirksmode has this well documented.

zzzzBov
  • 174,988
  • 54
  • 320
  • 367