admin管理员组

文章数量:1399278

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?

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?

Share Improve this question edited Apr 14, 2021 at 21:12 Sabir Hossain asked Feb 25, 2018 at 15:00 Sabir HossainSabir Hossain 1,2051 gold badge27 silver badges50 bronze badges 5
  • $("#yourUL").html('') before appending? – Varun Commented Feb 25, 2018 at 15:02
  • that was my practice code that I have tried so far. – Sabir Hossain Commented Feb 25, 2018 at 15:04
  • 1 add your html also – Vineesh Commented Feb 25, 2018 at 15:05
  • 1 Add your html which you are getting now and what you are expecting result form the raw html. Add live example using jsfiddle – Deep 3015 Commented Feb 25, 2018 at 15:05
  • please see the updated question... – Sabir Hossain Commented Feb 25, 2018 at 15:08
Add a ment  | 

2 Answers 2

Reset to default 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./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>

You could use jQuery .replaceWith() function.

simply use the following code

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

Refer this article .

本文标签: javascriptHow to replace all the ltligt elements of an ltulgt using JQueryStack Overflow