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

0

html:

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

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

    
asked by anonymous 06.04.2018 / 23:00

2 answers

1

You can use the "after" method of jQuery. 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>
    
06.04.2018 / 23:05
0

You can use the :nth-child() pseudo selector once you know which child "you want to enter 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>
    
06.04.2018 / 23:15