Locating DOM elements using selectors - Web APIs 编辑

The Selectors API provides methods that make it quick and easy to retrieve Element nodes from the DOM by matching against a set of selectors. This is much faster than past techniques, wherein it was necessary to, for example, use a loop in JavaScript code to locate the specific items you needed to find.

The NodeSelector interface

This specification adds two new methods to any objects implementing the Document, DocumentFragment, or Element interfaces:

querySelector()
Returns the first matching Element node within the node's subtree. If no matching node is found, null is returned.
querySelectorAll()
Returns a NodeList containing all matching Element nodes within the node's subtree, or an empty NodeList if no matches are found.
Note: The NodeList returned by querySelectorAll() is not live, which means that changes in the DOM are not reflected in the collection. This is different from other DOM querying methods that return live node lists.

You may find examples and details by reading the documentation for the Element.querySelector() and Element.querySelectorAll() methods, as well as in the article Code snippets for querySelector.

Selectors

The selector methods accept one or more comma-separated selectors to determine what element or elements should be returned. For example, to select all paragraph (p) elements in a document whose CSS class is either warning or note, you can do the following:

var special = document.querySelectorAll("p.warning, p.note");

You can also query by ID. For example:

var el = document.querySelector("#main, #basic, #exclamation");

After executing the above code, el contains the first element in the document whose ID is one of main, basic, or exclamation.

You may use any CSS selectors with the querySelector() and querySelectorAll() methods.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:135 次

字数:4111

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文