Why jQuery each() loop is getting all the elements of all iteration in each iteration?

43 views Asked by At

Why this script is not getting the H3 inside each iteration, but all the H3 of the all iterations each time?!

JS:

            $('a.grid-box').each(function(index){
                $( '.meta-info h3');
            });

HTML:

<div class="row">
      <a class="grid-box" href="">
        <div class="links-icons meta-info">
          <h3>Title 1</h3>
        </div>
      </a>

      <a class="grid-box" href="">
        <div class="links-icons meta-info">
          <h3>Title 2</h3>
        </div>
      </a>
etc...
</div>
1

There are 1 answers

4
Mitya On

Because your selector is making no reference to the a.grid-box iteration context, and so is searching globally.

Change

$('a.grid-box').each(function(index){
  $('.meta-info h3');
});

to

$('a.grid-box').each(function(index){
  $(this).find('.meta-info h3');
});

$('a.grid-box').each(function(index) {
  var h3 = $(this).find('.meta-info h3');
  console.log(h3.length, h3.text())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <a class="grid-box" href="">
    <div class="links-icons meta-info">
      <h3>Title 1</h3>
    </div>
  </a>

  <a class="grid-box" href="">
    <div class="links-icons meta-info">
      <h3>Title 2</h3>
    </div>
  </a>
  etc...
</div>

Also note the ;. typo in your original code.