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

问题描述 投票:2回答:1

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

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

javascript dom nodes
1个回答
2
投票

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

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>
© www.soinside.com 2019 - 2024. All rights reserved.