querySelectorALL()不支持活动节点,仅返回静态节点。MDN querySelectorALL
但是querySelector()可以支持活动节点MDN吗?不指定任何内容MDN querySelector
答案 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>