sahil sahil - 1 month ago 14
HTML Question

How to add li elements with a text in between existing li list using jquery?

I have 8 li elements with each having value from 1 to 8.



<ul>
<li>1</li>
<li class="even">2</li>
<li>3</li>
<li class="even">4</li>
<li>5</li>
<li class="even">6</li>
<li>7</li>
<li class="even">8</li>
</ul>





I want to insert li with text 'I am above x' above every li with even value. The desired li should look like



<ul>
<li>1</li>
<li>This is above 2</li>
<li class="even">2</li>
<li>3</li>
<li>This is above 4</li>
<li class="even">4</li>
<li>5</li>
<li>This is above 6</li>
<li class="even">6</li>
<li>7</li>
<li>This is above 8</li>
<li class="even">8</li>
</ul>





This can't be hardcoded as i have simplified the problem. Actually i want to dynamically add html above specific li elements.

I tried using
.insertBefore()
but this is not working.

("<li>x</li>").insertBefore$('#listing li.even');

Answer

You can use :nth-child() selector like this.

$('li:nth-child(even)').each(function() {
    var num = $(this).text();
  $(this).before('<li> This is before '+ num +'</li>');
})

$('li:nth-child(even)').each(function() {
  var num = $(this).text();
  $(this).before('<li> This is before ' + num + '</li>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li class="even">2</li>
  <li>3</li>
  <li class="even">4</li>
  <li>5</li>
  <li class="even">6</li>
  <li>7</li>
  <li class="even">8</li>
</ul>

Comments