How to append a listitem in first position of list using Jquery

后端 未结 3 981
醉酒成梦
醉酒成梦 2021-02-12 19:06

How to append a listitem in first position of list using Jquery?

  • First
  • Second
相关标签:
3条回答
  • 2021-02-12 19:46
    $('#mylist').prepend('<li></li>')
    
    0 讨论(0)
  • 2021-02-12 19:54

    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.

    0 讨论(0)
  • 2021-02-12 20:10

    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>

    0 讨论(0)
提交回复
热议问题