So I'm learning to manipulate the DOM and I noticed one interesting thing:
Let's say I want to set the name
attribute of an element by using the "." dot notation:
element.name = "someName";
console.log(document.getElementsByName("someName")[0]); // returns "undefined"??
However if I use the document.setAttribute()
method, it works fine:
element.setAttribute("name", "someName");
console.log(document.getElementsByName("someName")[0]); // returns the element like it should.
Not sure why the dot notation method doesn't work in the first case.
Why does this happen?
To extend the answers provided by some of the others ...
The attribute 'name' is only considered valid DOM for a few specific objects. According to https://developer.mozilla.org/en-US/docs/DOM/element.name those objects are:
For these objects you can set, get and change the name attribute using
object.name
BUT FOR ANY OTHER DOM OBJECT the attribute 'name' is a custom attribute and must be created usingSetAttribute()
or by adding it to the HTML declaration. Once it is created, you can acces it usingsetAttribute()
andgetAttribute()
or you can refer to its value directly usingobject.attributes.name.value
take a look at http://jsfiddle.net/radiotrib/yat72/1/ for an example. BTW - the alert box on load is intentional - check the code to see why ...My guess (because you didn't specify the element type) is the element normally does not have a
name
attribute, so setting the DOM property like that won't work.For example, setting the
name
property on aninput
element will work. Setting it on adiv
will not.It will work, however, with
setAttribute()
.jsFiddle.
when you use, element.name, you are accessing the property/creating a property named "name" and setting its value.
(Attempting to explain part of the above post a better, separately, since it is already went into -ve rating, and belief in that post will be less. Help improve this further.)
*** The
property
When you use, element.name, you are accessing a existing
property
named "name" or setting its value.*** The
attribute
but, while using,
element.setAttribute('name','someName')
, you are actually setting theattribute
named 'name'. This attribute can be an existing property toowhen you use, element.name, you are accessing the property/creating a property named "name" and setting its value.
but,
while using, element.setAttribute('name','someName'), you are actually setting the attribute 'name'.
IE8 and below treats the property and attribute as same, the bug has been fixed in IE9 and above.
Safari, FireFox, Chrome treat property and attribute differently.
However, you can always create a new property of your choice if you wish to do so.