I notice that javascript have several way to set and get attribute with an element.
I am not sure is there any diffrence between them. especially, is there cross browser problems.
I notice that javascript have several way to set and get attribute with an element.
I am not sure is there any diffrence between them. especially, is there cross browser problems.
Javascript guarantees element["attr"]
and element.attr
to be the same.
setAttribute()
, however, is not part of the language itself but of the DOM layer above it. There is no guarantee it's the same as a write to the attr
attribute. It can do more, or even less (i.e. not even update the attr
attribute of the object and require you to call getAttribute()
to get the value back).
In practice, the three ways are generally equivalent. Watch out for things like this, though.
Properties and attributes of DOM elements are quite different, and this difference is a source of some confusion.
An attribute represents the initial state of a particular characteristic of a DOM element. The corresponding property represents the current state of that characteristic. Since the current state is almost always what you want, the property is almost always what you should use. jQuery has a lot to answer for here: its unfortunately-named method attr()
uses properties in most cases, thus adding to the confusion.
The other major reason why you should use properties is that IE implements getAttribute()
and setAttribute()
incorrectly. Most attributes are mapped directly to properties in IE, which has a number of unfortunate effects such as meaning that setting an event handler attribute does not work correctly in IE. The following page has some useful information: http://reference.sitepoint.com/javascript/Element/setAttribute
There are other differences. For example, attributes/properties that deal with URLs have some discrepancies in how relative URLs are handled.
To see the difference between attributes and properties in standards-compliant browsers, consider the value of a text box:
<input type="text" id="textbox" value="foo">
var textBox = document.getElementById("textbox");
console.log(textBox.getAttribute("value")); // "foo"
console.log(textBox.value); // "foo"
Now, if the user types into the text box or the text box's value is changed using script, we see the property and attribute values diverge:
textBox.value = "bar";
console.log(textBox.getAttribute("value")); // "foo"
console.log(textBox.value); // "bar"
Setting the attribute value will now have no effect on the current value:
textBox.setAttribute("value", "baz");
console.log(textBox.getAttribute("value")); // "baz"
console.log(textBox.value); // "bar"