首页 > 解决方案 > document.queryselectorall 不适用于多个类 javascript

问题描述

我试图做一组具有相同类的元素我想遍历它们并添加一些类或执行一些任务但是 document.querySelectorAll() 不起作用,即使它返回节点列表长度 0 所以任何人都可以帮助我有了这个,我被困在了这一点上。

脚本

<script>
        var highlightedItems = document.querySelectorAll(".highlighted");

        highlightedItems.forEach(function (userItem) {
            deleteUser(userItem);
        });

        console.log(document.querySelectorAll('.headings'));
        if (document.querySelectorAll('.headings').length === 0) {
            //do stuff
            console.log("hello it is working");
        }
        document.querySelectorAll('.headings').forEach(item => {
            console.log("it is not good but its okay");

            item.addEventListener('click', event => {
                console.log('hello');
            })
        })

    </script>

即使我尝试使用 if 条件检查长度,它也显示为 0

html div

    <p class="highlighted">hello heloo helllo</p>
    <p class="highlighted">hello heloo helllo</p>
    <p class="highlighted">hello heloo helllo</p>
    <p class="highlighted">hello heloo helllo</p>
    <h1 class="animate__animated animate__bounce"> heloo</h1>
    <h1 class="mheadings">An animated element</h1>
    <h1 class="mheadings">An animated element</h1>
    <h1 class="mheadings">An animated element</h1>
    <h1 class="mheadings">An animated element</h1>
    <h1 class="mheadings animate__animated animate__bounce">An animated element</h1>
    <h1 class="mheadings animate__animated animate__bounce">An animated element</h1>

标签: javascripthtml

解决方案


您正在使用.headings选择元素,但您的 HTML 元素具有mheading

修复它:将您的类名更改mheading为选择器函数或headingHTML 代码中的名称。


推荐阅读