querySelector()返回静态节点或活动节点

时间:2018-07-12 09:31:36

标签: javascript dom nodes

由MDN指定的

querySelectorALL()不支持活动节点,仅返回静态节点。MDN querySelectorALL

但是querySelector()可以支持活动节点MDN吗?不指定任何内容MDN querySelector

1 个答案:

答案 0 :(得分:2)

querySelectorAll返回一个静态节点 list ,而getElementsByTagName返回一个 live 节点 list 列表是静态的还是活动的,而不是列表中的节点/元素。

querySelector返回的元素是DOM中的元素(与querySelectorAll列表中的元素一样)。它们是``实时的'',而不是快照或克隆-例如,如果它们已更改,则可以通过querySelector / querySelectorAll中的引用来查看这些更改。

示例:

const element = document.querySelector("input");
const staticList = document.querySelectorAll("input");
const liveList = document.getElementsByTagName("input");

element.addEventListener("input", () => {
  // Both of these are references to the live node in the DOM
  console.log(element.value);
  console.log(staticList[0].value);
});

document.getElementById("del").addEventListener("click", () => {
  // Removing the input
  document.body.removeChild(document.querySelector("input"));
  // It's still on the static list
  console.log("staticList.length = " + staticList.length); // 1
  // It's off the live list now
  console.log("liveList.length = " + liveList.length); // 0
  // Since we still have a reference to it, we can still see it's value
  console.log(element.value); // "what you typed"
});
Type something: <input type="text">
<br>then click this: <button id="del" type="button">Delete</button>