Peter Abraham
Peter Abraham

Reputation: 81

How to append li into ul

i have array values. i need to insert array values into li ,after that it will be appended into ul.

HTML

<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

Answers (6)

dfsq
dfsq

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

David Thomas
David Thomas

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

Maurice Perry
Maurice Perry

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));
    });
});

Fiddle

Upvotes: 0

SmartDev
SmartDev

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

Anoop Joshi P
Anoop Joshi P

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>");
    });
});

Fiddle

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

try

$("div").children().each(function () {
    $(this).append(function () {
        return $.map([1, 2, 3, 4, 5], function (i, val) {
            return "<li>" + i + "</li>";
        });
    });
});

DEMO

Upvotes: 0

Related Questions