jqueryjquery-selectorsnextuntil

JQuery .nextUntil() selecting heading into li


I'm trying to select all h3 tags under h2 tags even if into li whether ul or ol in a page, using .nextUntil().

HTML markup is like:

<h2></h2>
  <h3></h3>
  <h3></h3>
  <h3></h3>
<h2></h2>
  <h3></h3>
  <h3></h3>
  <h3></h3>
<h2></h2>
  <ol>
    <li>
     <h3></h3>
    </li>
    <li>
     <h3></h3>
    </li>
    <li>
     <h3></h3>
    </li>
  </ol>

Js is like:

var h2s = $('h2').toArray();

var h3s = [];

for (i = 0, i < h2s.length, i++){

  h3s.push($('h2').eq(i).nextUntil('h2', 'h3, li h3').toArray());

};

console.log(h3s);

The expected output is:

h3s[

 0: (3) [h3, h3, h3]
 1: (3) [h3, h3, h3]
 2: (3) [h3, h3, h3]

]

While the real output is:

h3s[

 0: (3) [h3, h3, h3]
 1: (3) [h3, h3, h3]
 2: []

]

Solution

  • I figured it out after many experiments, thanks to Bilel's each() & if(){}.

    here's a full sample https://playcode.io/533251 with a console.

    To get all the h3 tags below each h2 tag even if they are into <ol> or <ul>

    var h3s = [];
    
    var i = 0;
    
    $('h2').each(function(){
    
      if ($('h2').eq(i).nextUntil('h2').find('h3').length > 0) {
    
         h3s.push($('h2').nextUntil('h2').find('h3').toArray());
    
      } else {
    
         h3s.push($('h2').eq(i).nextUntil('h2', 'h3').toArray());
    
      } i++;
    
    });
    

    Or we can put the if(){} statement into simple for(){} loop depending on the length of an array of all h2 tags in the page

    var h2s = $('h2').toArray();
    
    var h3s = [];
    
    for (i = 0; i < h2s.length; i++) {
    
      if ($('h2').eq(i).nextUntil('h2').find('h3').length > 0) {
    
         h3s.push($('h2').nextUntil('h2').find('h3').toArray());
    
      } else {
    
         h3s.push($('h2').eq(i).nextUntil('h2', 'h3').toArray());
    
      }
    
    };