我正在尝试获取一个布尔值,让我知道父元素是否有子元素。一些限制是:
如果该框没有页脚元素,请添加一个类
<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>
答案 0 :(得分:1)
将上述评论移至实际答案:
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;
如果您在vanilla中做了很多这样的事情,为自己定义一个forEach
辅助函数是有意义的
function forEach(elems, fn){
var len = elems.length,
i = -1
while(++i < len) {
fn(elems[i])
}
}