pertrai1 pertrai1 - 3 months ago 17
Javascript Question

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"

  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>


Answer

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

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