document.getElementById是否返回实时dom元素? [英] Does document.getElementById return a live dom element?
问题描述
JavaScript中的 document.getElementById
是否返回实时DOM元素?我有兴趣了解性能原因
Does document.getElementById
in JavaScript return a live DOM element? I am interested to know for performance reason
推荐答案
标准和实时"之间的区别通常用于元素的列表. document.getElementById
返回对DOM节点的单个对象引用.一旦节点被获取,引用将始终指向同一节点.
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.
<div id="foo"></div>
以 JS为例:
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
由于元素的ID可能已更改,因此引用不会得到更新.
The references don't get updated just because the ID of the element might have changed.
这与诸如 document.getElementsByTagName
之类的东西形成对比,后者返回具有给定标记的元素列表.当元素添加到DOM中或从DOM中删除时,该列表将自动更新.
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.
这篇关于document.getElementById是否返回实时dom元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!