简体   繁体   中英

Any diffrence between element.setAttribute element['attr'] element.attr

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.

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"

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM