香草JS找到缺少儿童元素的元素

时间:2016-08-18 17:19:49

标签: javascript

我正在尝试获取一个布尔值,让我知道父元素是否有子元素。一些限制是:

  1. 可以有x个这样的"框"
  2. 检查并查看是否有任何包含页脚元素的框
  3. 如果该框没有页脚元素,请添加一个类

    <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>

1 个答案:

答案 0 :(得分:1)

将上述评论移至实际答案:

&#13;
&#13;
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')
}
&#13;
.no-footer { border: 3px solid blue; }
&#13;
<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>
&#13;
&#13;
&#13;

如果您在vanilla中做了很多这样的事情,为自己定义一个forEach辅助函数是有意义的

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