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

后端 未结 2 521
暖寄归人
暖寄归人 2020-12-06 20:48

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 br

2条回答
  •  没有蜡笔的小新
    2020-12-06 21:38

    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 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:

    
    
    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"
    

提交回复
热议问题