DeV*_*DeV 4 javascript dom nodes
MDN 指定的 querySelectorALL() 不支持活动节点,仅返回静态节点。MDN 查询选择器ALL
querySelector() 是否支持活动节点 MDN 未指定任何相关内容MDN querySelector
querySelectorAll返回一个静态列表(具体来说,一个 static NodeList),而(比如说)getElementsByTagName返回一个活动 列表(具体来说,一个 live HTMLCollection)。\xc2\xb9 这是静态或活动的列表,而不是节点/元素列表。
返回的元素querySelector是 DOM 中的元素(来自 的列表中的元素也是如此querySelectorAll)。它们是“实时的”,而不是快照或克隆\xc2\xa0\xe2\x80\x94,例如,如果它们发生了更改,您可以通过querySelector/的引用看到这些更改querySelectorAll。
例子:
\nconst element = document.querySelector("input");\nconst staticList = document.querySelectorAll("input");\nconst liveList = document.getElementsByTagName("input");\n\nelement.addEventListener("input", () => {\n // Both of these are references to the live node in the DOM\n console.log(element.value);\n console.log(staticList[0].value);\n});\n\ndocument.getElementById("del").addEventListener("click", () => {\n // Removing the input\n document.body.removeChild(document.querySelector("input"));\n // It\'s still on the static list\n console.log("staticList.length = " + staticList.length); // 1\n // It\'s off the live list now\n console.log("liveList.length = " + liveList.length); // 0\n // Since we still have a reference to it, we can still see it\'s value\n console.log(element.value); // "what you typed"\n});Run Code Online (Sandbox Code Playgroud)\r\nType something: <input type="text">\n<br>then click this: <button id="del" type="button">Delete</button>Run Code Online (Sandbox Code Playgroud)\r\n\xc2\xb9HTMLCollection实例始终处于活动状态。\xc2\xb2NodeList实例可以是活动的也可以是静态的(快照)。NodeList您从中获得的内容querySelectorAll是静态的,但NodeList您从(例如)childNodes属性中获得的内容Element是实时的。这是一个例子:
const container = document.getElementById("container");\n\nconsole.log(`Get a static list of the container\'s elements`);\nconst list = container.querySelectorAll("*");\nconsole.log(`It\'s a NodeList:`);\nconsole.log(list.constructor.name); // "NodeList"\nconsole.log(`With one element in it:`);\nconsole.log(list.length); // 1\n\nconsole.log(`Get a live list of children`);\nconst children = container.childNodes;\nconsole.log(`It\'s also a NodeList:`);\nconsole.log(children.constructor.name); // "NodeList"\nconsole.log(`With one element in it (so far):`);\nconsole.log(children.length); // 1\n\nconsole.log(`Add a new child`);\nconst p = document.createElement("p");\ncontainer.appendChild(p);\n\nconsole.log(`The static list still has one element:`);\nconsole.log(list.length); // 1\nconsole.log(`But the live list has two:`);\nconsole.log(children.length); // 2Run Code Online (Sandbox Code Playgroud)\r\n.as-console-wrapper {\n max-height: 100% !important;\n}Run Code Online (Sandbox Code Playgroud)\r\n<div id="container"><p></p></div>Run Code Online (Sandbox Code Playgroud)\r\n\xc2\xb2 “HTMLCollection实例始终处于活动状态。” - 事实上,规范并没有这么说。我的这一说法基于两点:
HTMLCollection规范描述的所有当前实例都是活动的,HTMLCollection将来不会添加新实例;这是一种传统类型。如果添加任何新集合,它们将被定义为Sequence<T>实例或NodeList实例。| 归档时间: |
|
| 查看次数: |
4884 次 |
| 最近记录: |