3

How can I replace all the li of a ul in JQuery, I don't want to add any new item to the list by using append rather I want a new list with new li elements in the same ul.

I have tried

for (index = 0; index < users.length; ++index) {
$('#users').replaceChild(users[index].UserName, $('#users').childNodes[index]);
}

#HTML

<div class="col-md-4" style="margin:auto">
    <h2 class="text-success">Users</h2>
    <ul id="users" style="list-style:none"></ul>
</div>
         

but it only add the last element of the Array to the ul, how to create a new ul when every time I got a new list?

Sabir Hossain
  • 1,183
  • 1
  • 25
  • 46

2 Answers2

5

It would be better if you include an example of your array. I made a snippet, hope it helps.

var array = ["New li 1", "New li 2", "New li 3"];

$('#load').click(function(){

  $('#list').empty();
  $.each(array, function( key, value ) {
    $('#list').append('<li>' + value + '</li>');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul id="list">
  <li>Old li 1</li>
  <li>Old li 2</li>
  <li>Old li 3</li>
</ul>

<button id="load">Load array</button>
SomeRSGuy
  • 590
  • 7
  • 19
1

You could use jQuery .replaceWith() function.

simply use the following code

$('#users').replaceWith( "<li>New Item</li>" );

Refer this article .

Jayampathy Wijesena
  • 1,670
  • 1
  • 18
  • 26
  • If you can read this article (http://api.jquery.com/replacewith/) it clearly explains the theory with example – Jayampathy Wijesena Feb 26 '18 at 07:09
  • if did you get the point of `replaceWith()` then answer the question according to it's requirement if you can... – Sabir Hossain Feb 26 '18 at 07:17