简体   繁体   English

Vanilla JS查找缺少子元素的元素

[英]Vanilla JS Find Element with Missing Child Element

I am trying to get a boolean that will let me know if a parent element has a child element. 我正在尝试获取一个布尔值,该布尔值将让我知道父元素是否具有子元素。 Some of the constraints are: 一些约束是:

  1. There can be x number of these "boxes" 这些“盒子”可以是x个
  2. Check and see for any of the boxes have a footer element 检查并查看是否有任何框都有页脚元素
  3. If the box does not have a footer element, add a class 如果该框没有页脚元素,请添加一个类

    <div class="data-trend"> <header></header> <div class="main"></div> <footer></footer> </div>

    <div class="data-trend"> <header></header> <div class="main"></div> <footer></footer> </div>

    <div class="data-trend"> <header></header> <div class="main"> <span class="glyphicons"><span> <!-- On the glyphicons I would add class if there is no footer --> </div> <!-- notice no footer --> </div>

Moved the above comment into an actual answer: 将以上评论移至实际答案:

 var elems = document.querySelectorAll('.data-trend'), len = elems.length, i = -1 while(++i < len) { if(!elems[i].querySelector('footer')) elems[i].classList.add('no-footer') } 
 .no-footer { border: 3px solid blue; } 
 <div class="data-trend"> <header>Testing</header> <div class="main"></div> <footer>Footer</footer> </div> <div class="data-trend"> <header>Testing</header> <div class="main"></div> <footer>Footer</footer> </div> <div class="data-trend"> <header>Testing</header> <div class="main"> <span class="glyphicons"><span> </div> </div> 

If you're doing a lot of this in vanilla, it makes sense to define a forEach helper function for yourself 如果您在香草中做很多事情,那么为自己定义一个forEach帮助器函数是很有意义的

function forEach(elems, fn){
  var len = elems.length,
      i = -1
  while(++i < len) {
    fn(elems[i])
  }
}

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

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