How to add two li in a ul dynamically with jQuery?

Asked

Viewed 142 times

0

html:

<ul>
  <li>1</li>
  <li>2</li>
  Adicionar aqui
  <li>5</li>
</ul>

I need to add two li where it is written: "Add here". Does anyone know how to do this using jQuery?

2 answers

1


You can use jQuery’s "after" method. Example:

$(document).ready(function() {
  var $li = $('ul li').eq(1);
  
  $('button').click(function() {
    $li.after('<li>' + $('ul li').length + '</li>');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>1</li>
  <li>2</li>
  <li>5</li>
</ul>
<button>Adicionar</button>

  • It worked as expected. Thank you!

0

You can use the pseudo selector :nth-child() once you know from which "child" you want to insert content.

$('ul > li:nth-child(2)').after(`
    <li>3</li>
    <li>4</li>
`)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li>1</li>
  <li>2</li>
  <li>5</li>
</ul>

  • 1

    There you are entering inside the second <li> and not after.

  • Yes, this wrong the right would be .after()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.