javascript - document.querySelector 是如何实现的?

标签 javascript algorithm dom browser tree

我想这个问题的答案取决于您使用的是什么浏览器,但我想这只会让它变得更加有趣。

我想知道 querySelector()方法实际执行。同样,我很好奇 querySelectorAll()和其他方法,如 getElementById()getElementByClassName()等等

它是深度优先搜索、广度优先搜索,还是利用一些辅助数据结构,如全局哈希表作为注册表?

最佳答案

您要求的所有信息都在您提供的链接中:

querySelector: Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors.


querySelectorAll: Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.


getElementById: Returns a reference to the element by its ID; the ID is a string which can be used to identify the element; it can be established using the id attribute in HTML, or from script.

作为 ID 应该唯一 - 没有顺序问题


getElementsByClassName: Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

关于javascript - document.querySelector 是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34756944/

相关文章:

javascript - 单个 Electron createWindow() 实例变量

javascript - 我使用 "this"关键字和 "call"方法传递一些函数和元素

javascript - AngularJS:如何从过滤器中获取 DOM 元素

javascript - 将字符串项添加到appendChild li元素

javascript - JQuery 检查多个 Selects 值

java - 比较两种反向链表算法内部的空间复杂度

c++ - 如何随机洗牌 map 中的值?

c++ - 在不止一个回文的情况下寻找最长但字典序最小的回文

JavaScript:在单击事件上获取父元素值

javascript - JS/JQuery - 在短时间内点击显示按钮