Does document.getElementById return a live dom element?

后端 未结 1 1398
囚心锁ツ
囚心锁ツ 2021-01-05 01:26

Does document.getElementById in JavaScript return a live DOM element? I am interested to know for performance reason

相关标签:
1条回答
  • 2021-01-05 01:54

    The distinction between standard and "live" is usually used for lists of elements. document.getElementById returns a single object reference to a DOM node. Once the node is acquired the reference will always point to the same node.

    HTML for the example:
    <div id="foo"></div>
    
    JS for the example:
    var foo,
        bar;
    foo = document.getElementById('foo'); //gets the div
    bar = document.getElementById('bar'); //null
    foo.setAttribute('id', 'bar');
    console.log(foo.id); //'bar'
    console.log(bar.id); //TypeError
    

    The references don't get updated just because the ID of the element might have changed.

    This is in contrast to something like document.getElementsByTagName which returns a list of elements with the given tag. The list will automatically update when elements are added to or removed from the DOM.

    0 讨论(0)
提交回复
热议问题