我试图做的是一组具有相同类的元素,我希望迭代它们并添加一些类或执行一些任务,但是document.querySelectorAll()不起作用,即使它返回的节点列表长度为0,所以任何人都可以在这方面帮助我,我在这一点上被困住了。
Js脚本
<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
,或者在HTML代码中将类名更改为Heading
。
要使用queryselectorall,您需要使用TagName.className。
在你的情况下,请试着-
document.querySelectorAll('p.highlighted')
或
document.querySelectorAll('h1.mheadings')
另外,请使用正确的类名,因为我在代码中没有找到你提到的类。