0

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 !

2
  • 2
    Please edit your question by providing us an example of the json you want to display Commented Nov 3, 2013 at 11:57
  • One change I can suggest even just with the info in the question: Use value.title rather than json[key].title. Commented Nov 3, 2013 at 12:00

1 Answer 1

1

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));
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.