由MDN指定的querySelectorALL()不支持活动节点,仅返回静态节点。MDN querySelectorALL
但是querySelector()可以支持活动节点MDN而不指定任何内容吗MDN querySelector
querySelectorAll
返回一个静态节点list,而(说)getElementsByTagName
返回一个live节点list。 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>