user1807880 user1807880 - 6 months ago 39
Javascript Question

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!

Answer

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>

Comments