poutyboi
poutyboi

Reputation: 149

jquery append nested elements

I need to append nested element to the page

I am using the append function, but running into an error trying to pass an array to it.

<div id="area">
</div>

var data = [{"class":"a", "href":"http://google.com"}, {"class":"b", "href":"http://yahoo.com"}];

$('#area').append(
    $('<ul>').append(
        $(data).each(function(i, val) {
            $('<li>', {class: val["class"]}).append(
                $('<a>', {href: val["href"]})
        })
    )
)

When I do this I get an error on the input of the append function because I am passing .each. I need to do this dynamically based on a given array to add a set of nested elements so in the end it would be.

<div id="area">
    <ul>
        <li class="b">
            <a href="http://yahoo.com"></a>
        </li>
        <li class="a">
            <a href="http://google.com"></a>
        </li>
    </ul>
</div>

So I am wondering how to pass .each to append, or do something similar in a different way.

Thanks to all in advanced!

Upvotes: 0

Views: 3229

Answers (2)

T J
T J

Reputation: 43156

Nothing in your code is appending the <li>s to <ul> because $(data).each returns the data array wrapped in jQuery object.

You should use $.each to iterate over non-jQuery objects, and always try to cache references and do manipulations in memory before attaching to DOM.

Note that unlike the other answer, below code manipulates the actual DOM only once.

var data = [{
  "class": "a",
  "href": "http://google.com"
}, {
  "class": "b",
  "href": "http://yahoo.com"
}];
var $ul = $('<ul>');
$.each(data, function(i, val) {
  var $li = $('<li>', {
    class: val["class"]
  });
  $li.append(
    $('<a>', {
      href: val["href"],
      text: val["href"]
    }));
  $ul.append($li);
});
$('#area').append($ul);
//--------^--- one time DOM manipulation
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="area">

</div>

Upvotes: 1

guradio
guradio

Reputation: 15555

var data = [{
  "class": "a",
  "href": "http://google.com"
}, {
  "class": "b",
  "href": "http://yahoo.com"
}];
var ul = $('<ul/>'); //create the ul
$(data).each(function(i, val) { //loop the data
  ul.append('<li class=' + val.class + '><a href=' + val.href + '>' + val.href + '</li>'); //append each value on li the class and href
  $('#area').append(ul) //append the ul to the div
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="area">
</div>

Upvotes: 1

Related Questions