Reputation: 41
I'm trying to display in a list all the elements of my json.
I have a var "json" containing all my data.
What I exactly want is display the datas like this :
<ul>
<li>title + "of the first element"</li>
<li>title + "of the second element"</li>
<li>title + "of the third element"</li>
</ul>
Every time I try something with a simple "for", it only display me the last element.
The closest solution I had was with this I think:
function displayJson(){
$.each(json, function(key, value) {
$(this).html("<li>" + json[key].title + "</li>");
});
}
I'm a beginner, any help would be really appreciated !
Upvotes: 0
Views: 1425
Reputation: 1074258
Within the function you're giving $.each
, this
will be the value of the entry in the json
object, not a DOM element, so you can't generate the output that way.
Assuming that json
refers to an object that contains objects, each of which has a title
property, then:
var $ul = $("some selector for the list");
var json = /*...wherever you're getting the object from... */;
displayJson($ul, json);
function displayJson($ul, json) {
$ul.empty(); // If it might have something in it
$.each(json, function(key, value) {
$ul.append($("<li>").html(value.title));
});
}
Upvotes: 1