掌握 JavaScript 中的 querySelector 和 querySelectorAll

JavaScript 中的 querySelector 和 querySelectorAll

`querySelector` 和 `querySelectorAll` 方法是 JavaScript 中用于选择 DOM 元素的强大工具。它们允许开发人员使用 CSS 选择器来识别和操作 HTML 元素。

1. 查询选择器

`querySelector` 方法选择与指定 CSS 选择器匹配的**第一个**元素。

句法:

document.querySelector(selector);
  • selector:表示 CSS 选择器的字符串(例如“#id”、“.class”、“tag”)。
  • 例子:

    First paragraph

    Second paragraph

    const firstText = document.querySelector(".text");
    console.log(firstText.textContent); // Output: First paragraph

    2. querySelectorAll

    `querySelectorAll` 方法选择与指定 CSS 选择器匹配的**所有**元素并将它们作为 **NodeList** 返回。

    句法:

    document.querySelectorAll(selector);
  • selector:代表 CSS 选择器的字符串。
  • 例子:

    const allTexts = document.querySelectorAll(".text");
    allTexts.forEach((text) => console.log(text.textContent));
    // Output:
    // First paragraph
    // Second paragraph

    访问 NodeList 中的元素:

    const secondText = allTexts[1];
    console.log(secondText.textContent); // Output: Second paragraph

    3. querySelector 和 querySelectorAll 的区别

    4. 组合选择器

    您可以组合 CSS 选择器以进行更具体的查询。

    例子:

    const containerParagraph = document.querySelector("#container .text");
    console.log(containerParagraph.textContent); // Output: First paragraph

    5.常见用例

    按 ID 选择:

    const header = document.querySelector("#header");

    按类别选择:

    const buttons = document.querySelectorAll(".button");

    按标签名称选择:

    const paragraphs = document.querySelectorAll("p");

    属性选择器:

    const checkedBox = document.querySelector("input[type='checkbox']:checked");

    第 N 个子选择器:

    const secondItem = document.querySelector("ul li:nth-child(2)");

    6. 从 querySelectorAll 迭代元素

    由于“querySelectorAll”返回一个NodeList,因此您可以使用“forEach”、“for...of”或索引循环遍历它。

    例子:

    const listItems = document.querySelectorAll("ul li");
    listItems.forEach((item, index) => {
      console.log(`Item ${index + 1}: ${item.textContent}`);
    });

    7. 实时收集与静态收集

  • querySelectorAll 返回一个静态 NodeList,这意味着如果 DOM 发生变化,它也不会更新。
  • 使用 getElementsByClassName 或 getElementsByTagName 进行实时收集。
  • 例子:

    const items = document.querySelectorAll(".item");
    console.log(items.length); // Static, won't change if new .item is added later

    8.错误处理

    如果没有找到匹配的元素:

  • querySelector:返回 null。
  • querySelectorAll:返回一个空的NodeList。
  • 例子:

    const missingElement = document.querySelector(".missing");
    console.log(missingElement); // Output: null
    
    const missingElements = document.querySelectorAll(".missing");
    console.log(missingElements.length); // Output: 0

    9. 总结

  • 使用 querySelector 选择单个元素,使用 querySelectorAll 选择多个元素。
  • 两种方法都支持强大的 CSS 选择器,可实现精确定位。
  • querySelectorAll 返回一个静态 NodeList,可以轻松进行迭代。
  • 它们是现代 DOM 操作的多功能工具,并且通常比 getElementById 或 getElementsByClassName 等旧方法更受欢迎。
  • 掌握这些方法将使你的JavaScript代码更干净,更高效!

    **嗨,我是 Abhay Singh Kathayat!**

    我是一名全栈开发人员,精通前端和后端技术。我使用多种编程语言和框架来构建高效、可扩展且用户友好的应用程序。

    请随时通过我的商务电子邮件联系我:kaashshorts28@gmail.com。