简体   繁体   中英

How to prepend HTML `<li>` to `<ul>` using jQuery?

I need to append an <li> element to multiple <ul> using a for-loop in jQuery.

Code Snippet:

JQuery:

var lists = $('ul.menu');

for(var i=0; i<lists.length; i++){
    var lnk = "<li>All</li>";
    lnk = $('<div />').html(lnk).text();
    lists[i].prepend(lnk);
}

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
    <li>Graphics</li>
    <li>Videos</li>
    <li>Programming</li>
</ul>
<hr>
<ul class="menu">
    <li>Our Story</li>
    <li>About Us</li>
</ul>

As per code <li> inserts as the proper text, but is been formatted as plain text instead of an <li> .

What am I doing wrong? How to correct my mistakes?

A slightly more jQuery-ish alternative to TJ Crowder's solution ...

 $('ul.menu').each(function() { $(this).prepend("<li>All</li>"); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu"> <li>Graphics</li> <li>Videos</li> <li>Programming</li> </ul> <hr> <ul class="menu"> <li>Our Story</li> <li>About Us</li> </ul> 

You're calling the raw DOM prepend (which only exists on modern browsers), because lists[i] accesses the raw ul element. You're also just taking the text of what you want to prepend, rather than including any li markup. You probably want to:

  1. Call jQuery's prepend , and

  2. Include the li in what you're prepending

Example:

 var lists = $('ul.menu'); for(var i=0; i<lists.length; i++){ var lnk = "<li>All</li>"; lists.eq(i).prepend(lnk); } 
 /* No CSS */ 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="menu"> <li>Graphics</li> <li>Videos</li> <li>Programming</li> </ul> <hr> <ul class="menu"> <li>Our Story</li> <li>About Us</li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM