Reputation: 81
i have array values. i need to insert array values into li ,after that it will be appended into ul.
<div>
<ul></ul>
<ul></ul>
</div>
Array value x=[1, 2, 3, 4, 5];
Need Output
<div>
<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>
<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>
</div>
I have tried some thing i wont work. fiddle link
Upvotes: 1
Views: 1490
Reputation: 193261
You can use append
method which can also accept an array of DOMElements/jQuery Objects:
var x = [1, 2, 3, 4, 5];
$("div ul").append(x.map(function (el) {
return $('<li>').text(el);
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul></ul>
<ul></ul>
</div>
Upvotes: 3
Reputation: 253308
I'd suggest:
var x = [1, 2, 3, 4, 5];
x.forEach(function(num){
$('ul').append('<li>' + num + '</li>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul></ul>
<ul></ul>
</div>
Or, perhaps:
var x = [1, 2, 3, 4, 5];
$('ul').html(function() {
return '<li>' + x.join('</li><li>') + '</li>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<ul></ul>
<ul></ul>
</div>
References:
Upvotes: 1
Reputation: 32831
Another example:
var x=[1, 2, 3, 4, 5];
$("div ul").each(function () {
var $ul = $(this);
$.each(x, function() {
$ul.append($("<li/>").text(this));
});
});
Upvotes: 0
Reputation: 2862
var x = [1, 2, 3, 4, 5];
$("div ul").each(function () {
for(var i=0; i < x.length; i++) {
$(this).append("<li>" + x[i] + "</li>");
}
});
Upvotes: 0
Reputation: 25527
Loop through each elements and append like this
var x = [1, 2, 3, 4, 5];
$("div ul").each(function() {
var ul = this;
$.each(x, function(i, val) {
$(ul).append("<li>" + val + "</li>");
});
});
Upvotes: 0
Reputation: 9637
try
$("div").children().each(function () {
$(this).append(function () {
return $.map([1, 2, 3, 4, 5], function (i, val) {
return "<li>" + i + "</li>";
});
});
});
Upvotes: 0