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?
- $("#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
2 Answers
Reset to default 5It 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
版权声明:本文标题:javascript - How to replace all the <li> elements of an <ul> using JQuery? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744205679a2595176.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论