简体   繁体   English

根据子元素的数量检索 DOM 元素

[英]Retrieve DOM element according to the number of its children

I want to get the DOM elements that have more than 5 children and add a class name to only those elements.我想获取具有超过 5 个子元素的 DOM 元素,并仅为这些元素添加一个 class 名称。 For example,例如,

<div class="parent">
    <span>child</span>
    <span>child</span>
    <span>child</span>
</div>

<div class="parent">
    <span>child</span>
    <span>child</span>
    <span>child</span>
    <span>child</span>
    <span>child</span>
    <span>child</span>
</div>

<div class="parent">
    <span>child</span>
    <span>child</span>
</div>

In this case I'd like to add a class name to the second div above that has 6 children spans .在这种情况下,我想将spans名称添加到上面有 6 个子 span 的第二个div中。

I've tried the following:我尝试了以下方法:

const parents = document.querySelector(".parent");

if (parents.childElementCount > 5) {
    parents.classList.add('reduce-size');
}

You have 3 div with the class parent.您有 3 个 div 与 class 父级。 So I think you have to use a querySelectorAll('.parent') and a loop after.所以我认为你必须使用 querySelectorAll('.parent') 和之后的循环。 Someting like this maybe可能是这样的

const parents = document.querySelectorAll(".parent");
for (let i = 0; i < parents.length; i++) {
  if (parents[i].childElementCount > 5) {
  cityLocationTitle.classList.add('.reduce-size');
}
}
const parents = document.querySelectorAll(".parent");

parents.forEach(el => {
 if(el.childNodes.length > 5){
   el.classList.add('.reduce-size');
 }
});

querySelector only returns the first matching element. querySelector只返回第一个匹配的元素。 You need to use querySelectorAll together with a loop:您需要将querySelectorAll与循环一起使用:

 const parents = document.querySelectorAll(".parent"); for (let parent of parents) { if (parent.childElementCount > 5) { console.log("do stuff here"); } }
 <div class="parent"> <span>child</span> <span>child</span> <span>child</span> </div> <div class="parent"> <span>child</span> <span>child</span> <span>child</span> <span>child</span> <span>child</span> <span>child</span> </div> <div class="parent"> <span>child</span> <span>child</span> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM