javascript - 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>
解决方案
您正在使用.headings
选择元素,但您的 HTML 元素具有mheading
类
修复它:将您的类名更改mheading
为选择器函数或heading
HTML 代码中的名称。
推荐阅读
- laravel - 在下拉列表中显示特定数据
- vba - 从 Access VBA 在 SQL 中保存 jpg
- wordpress - 删除分页的最后一页
- sql - “SELECT TOP”查询的意外 SQL 行为
- python - 填充颜色不适用于我的函数(Python 乌龟图形)
- unix - Ocaml 客户端-服务器:客户端在尝试连接时返回 EAGAIN
- mysql - 更新 MySQL 中 2 个表之间的电子邮件匹配 - 黑名单
- javascript - NextJS - 导出被破坏(没有 CSS,没有 JS)
- c++ - 用于透视的倒置几何 gBuffer 位置。正字法好吗?
- python - 蟒蛇 | 制作列表的百分比