Fetching data from api as json, but html nesting is off

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
}

Answers


According to .append(), ul.append(listItem, linkFromJson) inserts all content to the end of the ul element 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>

var listItem = document.createElement('li');
listItem.append(linkFromJson);
ul.append(listItem);

Need Your Help

Java workaround for subclass forced to call super() in constructor?

java subclass super superclass

I am editing a program that uses a RandomAccessFile object, and I want to come up with my own RandomAccessFile class that uses a different source for the data other than a file object (it's an Amazon

Export Excel file to create html webpages

html xml excel export

I'd like to know how you would try to solve the following problem:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.