Nitish Kumar Nitish Kumar - 7 months ago 27
Javascript Question

Adding HTML code using for loop in jquery

I'm trying to add li elements in a html codes to a div element, following is my html code:

Place where the elements to be added:

<div class="form-body" id="nitspopupmenu"></div>


Elements of ul:

<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right" id="nitsmenu" data-nitspagelabel="1">
<li class="scroll active"><a href="#navigation">Home</a></li>
<li class="scroll"><a href="#aboutus">About Us</a></li>
<li class="scroll"><a href="#services">Services</a></li>
<li class="scroll"><a href="#ourteam">Our Team</a></li>
<li class="scroll"><a href="#portfolio">Portfolio</a></li>
<li class="scroll"><a href="#clients">Clients</a></li>
<li class="scroll"><a href="#blog">Blog</a></li>
<li class="scroll"><a href="#contact">Contact</a></li>
</ul>
</div>


My Jquery code:

$(e).fadeIn(400);

$('#nitspagesorter').fadeIn(400).css({
'top': mouseY,
'left': mouseX
}).draggable();

$('#nitsmenubutton').hide();

var licount = $("#nitsmenu li").length;
for (i = 0; i < licount; i++) {
var lielem = $("#nitsmenu li").text();
var element = $(lielem).text();
$("#nitspopupmenu").html("<div class='form-group'><div class='pagesmenu selected'><span><i class ='fa fa-bars'></i>" + lielem + "");
}


I'm poping up the content to popup box, I'm getting the
li
name properly but its showing only the last element i.e. Contact,
$("#nitspopupmenu").html("<div class='form-group'><div class='pagesmenu selected'><span><i class ='fa fa-bars'></i>" + lielem + "");
is executing at last or might be replacing the content everytime and showing the last result

Please help

Answer

I think you should use append() over html()

for (i = 0; i < licount; i++) {
    var lielem = $("#nitsmenu li").text();
    var element = $(lielem).text();
    $("#nitspopupmenu").append("<div class='form-group'><div class='pagesmenu selected'><span><i class ='fa fa-bars'></i>" + lielem + "");
}

You should put all string with in one line, if multiple lines required then concat with + sign

Comments