I’m trying to nest an <a> tag within my <li> tag when looping through some JSON data, but it isn’t:
var ul = $('<ul/>');
$.each(data.headlines, function() {
var linkFromJson = "<a>" + this.headline + "</a>";
linkFromJson = $(linkFromJson).attr("href", this.links.web.href).attr("target", "_blank");
var listItem = document.createElement('li');
ul.append(listItem, linkFromJson);
});
// append this list to the document body
$('body').append(ul);
What i get is a <li></li> and the <a> tag follows, but it displays the hyperlink correctly. When I write the code out to nest the json, it gives me [object][Object] back after it loops through the items for each <li> tag.
What am I doing wrong?
Thanks!
EDIT: I figured it out, using .html to insert the built link inside the <li>, and them append the <li>s into the <ul>:
var ul = $('<ul/>');
$.each(data.headlines, function() {
var linkFromJson = "<a>" + this.headline + "</a>";
linkFromJson = $(linkFromJson).attr("href", this.links.web.href).attr("target", "_blank");
var listItem = $('<li/>');
$(listItem).html(linkFromJson);
ul.append(listItem);
});
// append this list to the document body
$('body').append(ul);
},
error: function() {
// handle the error
}
According to
.append(),ul.append(listItem, linkFromJson)inserts all content to the end of theulelement sequentially. It will not nest the given content inside each other.To achieve that, you must first append
<a>to<li>and then append the resulting<li>to<ul>