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=".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?
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./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?
Share Improve this question edited Sep 9, 2018 at 20:15 Pac0 23.3k9 gold badges73 silver badges83 bronze badges asked Sep 9, 2018 at 18:15 nucleic550nucleic550 851 silver badge7 bronze badges 3- Not able to replicate – brk Commented Sep 9, 2018 at 18:20
-
Why are you doing
lnk = $('<div />').html(lnk).text();
? It seems like you probably have a reason for that, but it's not clear what it is. (Genuinely.) – T.J. Crowder Commented Sep 9, 2018 at 18:22 - In light of your answer, I've removed that line and the code works fine. Thanks! – nucleic550 Commented Sep 9, 2018 at 18:39
2 Answers
Reset to default 3You'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:
Call jQuery's
prepend
, andInclude 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./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>
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./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>