What is happening behind .setAttribute vs .attribute=?

前端 未结 2 2077
囚心锁ツ
囚心锁ツ 2020-12-02 23:54

Description:

I am using simple javascript to set a the value of an input. I am using multiple methods that appear to be th

2条回答
  •  再見小時候
    2020-12-03 00:38

    It's important to take note of the differences between attributes and properties.

    The value attribute

    The value attribute of an , visible in the HTML representation of the element, is mapped to the defaultValue property. For example:

    var i = document.createElement('input');
    i.setAttribute('value', 'foo');
    console.log(i.defaultValue, i.getAttribute('value')); // "foo foo"
    
    i.defaultValue = 'bar';
    console.log(i.defaultValue, i.getAttribute('value')); // "bar bar"
    

    The value property

    The value property mirrors the defaultValue property (and value attribute) until it's explicitly been given a value, so:

    var i = document.createElement('input');
    i.defaultValue = 'foo';
    console.log(i.value); // "foo"
    
    i.value = 'bar';
    i.defaultValue = 'foo';
    console.log(i.value); // "bar"
    

    This is another way of looking at it:

    
           ↑↓
    input.defaultValue = "foo";
            ↓
    input.value
      get(): value === undefined ? input.defaultValue : value
      set(newValue): value := newValue
    

    Anchors

    When using anchors, the href attribute and href property update each other, but in a different way, e.g.:

    var a = document.createElement('a');
    a.setAttribute('href', '/test');
    console.log(a.href); // "http://stackoverflow.com/test"
    
    a.href = '/test';
    console.log(a.getAttribute('href')); // "/test"
    

    Other elements

    Here's a (partial) list of attributes and their corresponding properties:

    element  | attribute | property
    ---------+-----------+----------------
    option   | selected  | defaultSelected (bool)
    label    | for       | htmlFor
    input    | checked   | defaultChecked (bool)
    select   | multiple  | multiple (bool)
    li       | value     | value (int)
    

    As you can see, whereas the attributes are always strings, the corresponding properties may be of other types.

提交回复
热议问题