Adam Adam - 2 months ago 16
jQuery Question

Loop through multiple ul list

I have multiple

<ul>
list with the same number of
<li>
elements:

<ul id='first'>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

<ul id='second'>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
</ul>

<ul id='third'>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>


I want to first get the first
<li>
element of each
<ul>
(1,5,9), then the second for each (2,6,10) and so on.

I know that I can get the all
<li>
elements of a
<ul>
by
$('#first li').each(...)
. Is there a similar command to get the
<li>
elements in the above described order?

Answer

You can use eq() (or :eq()) method along with each() method.

// iterate ove li elements
$('#first li').each(function(i) {
  console.log(
    // get text from li
    $(this).text(),
    // get li from second based on index and get text
    $('#second li').eq(i).text(), //  you can also use `$('#second li:.eq(' + i + ')')`
    // get li from third based on index and get text
    $('#third li').eq(i).text());
});

// iterate ove li elements
$('#first li').each(function(i) {
  console.log(
    // get text from li
    $(this).text(),
    // get li from second based on index and get text
    $('#second li').eq(i).text(),
    // get li from third based on index and get text
    $('#third li').eq(i).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='first'>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

<ul id='second'>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

<ul id='third'>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ul>


Or you can use text() method with callback instead of each() method.

// iterate over li elements where first argument holds index
// and second argument holds the text content
$('#first li').text(function(i, v) {
  console.log(
    v,
    // get li from second based on index and get text
    $('#second li').eq(i).text(),
    // get li from third based on index and get text
    $('#third li').eq(i).text());
});

// iterate ove li elements
$('#first li').text(function(i, text) {
  console.log(
    text,
    // get li from second based on index and get text
    $('#second li').eq(i).text(),
    // get li from third based on index and get text
    $('#third li').eq(i).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='first'>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>

<ul id='second'>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
</ul>

<ul id='third'>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
</ul>

Comments