Any Diffrence Between Element.setAttribute Element['attr'] Element.attr
Solution 1:
Properties and attributes of DOM elements are quite different, and this difference is a source of some confusion.
One problem is that not every attribute maps to a property of the same name. For example, the value
attribute of an <input>
element maps to the defaultValue
property, while the value
property does not map to any attribute (except in old IE: see below).
The other major reason why you should use properties is that older versions of IE (<=7 and compatibility modes in later versions) implement getAttribute()
and setAttribute()
incorrectly. Most attributes are mapped directly to identically-named 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"
console.log(textBox.defaultValue); // "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"
console.log(textBox.defaultValue); // "foo"
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"
console.log(textBox.defaultValue); // "baz"
Solution 2:
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.
Post a Comment for "Any Diffrence Between Element.setAttribute Element['attr'] Element.attr"