Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Each Loop Causing Problem

Hello – My question is best summarize with the intended output and the real output. Any clue why it's doing this, using the following HTML and JS code?

HTML Code:

<h3>CATEGORY 1</h3>
<p>Item 1</p>
<p>Item 2</p>

<h3>CATEGORY 2</h3>
<p>Item 3</p>
<p>Item 4</p>

<h3>CATEGORY 3</h3>
<p>Item 5</p>
<p>Item 6</p>

JavaScript / jQuery Code:

$(".h3").each(function () {

  // Display H3 Text
  console.log($(this).text());

  $(this).siblings('p').each(function () {
    if ( $(this).next().is('h3') ) {

      // Display Last Paragraph Text Before <H3>
      console.log($(this).text());

      // Break the Each Loop, Go to next H3
      return false;
    }
    else {

      // Display Paragraph Text
      console.log($(this).text());
    }
  });
});

Intended Output:

CATEGORY 1
Item 1
Item 2
CATEGORY 2
Item 3
Item 4
CATEGORY 3
Item 5
Item 6

Real (Unintended) Output:

CATEGORY 1
Item 1
Item 2
CATEGORY 2
Item 1
Item 2
CATEGORY 3
Item 1
Item 2

Thanks.

like image 359
Mike B. Avatar asked Feb 27 '23 16:02

Mike B.


1 Answers

Because siblings() selects all siblings, all previous and all following. I think you need nextAll():

Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.


Demo

$("h3").each(function () {

  // Display H3 Text
  console.log($(this).text());

  $(this).nextAll('p').each(function () {
    if ( $(this).next().is('h3') ) {

      // Display Last Paragraph Text Before <H3>
      console.log($(this).text());

      // Break the Each Loop, Go to next H3
      return false;
    }
    else {

      // Display Paragraph Text
      console.log($(this).text());
    }
  });
});

gives:

CATEGORY 1
Item 1
Item 2

CATEGORY 2
Item 3
Item 4

CATEGORY 3
Item 5
Item 6
like image 61
Felix Kling Avatar answered Mar 10 '23 14:03

Felix Kling