How to append a listitem in first position of list using Jquery?
- First
- Second
-
$('#mylist').prepend('<li></li>')
You are selecting the second li
element, try this:
$('#mylist li:eq(0)').before("<li>first</li>");
//or $('#mylist li:first')...
or you can use prepend
method.
This snippet will solve the problem. Or go to the link to learn more.
$('#mylist').prepend('<li>New Item</li>');
//use jQuery's prepend method.
$('button').on('click',function(){
$('#mylist').prepend('<li>New Item 1 added</li>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html>
<body>
<ul id="mylist">
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
<li>Fourth Item</li>
</ul>
<button> click to add first li</button>
</body>
</html>