user123 user123 - 1 month ago 8
HTML Question

jQuery each() loop iterating more than expected

In the below code, I take a div, clone it for as many items within the new javascript object, populate each clone with a title and post, and then I clear the first parent.

console.log(message.length)
after parsed returns 4. So I expect the loop to iterate 4 times, leaving 4 divs of title and post. However, this code returns 1 div of "first note" and "test message...", 2 divs of "second test" and "some more...", 4 divs of "third test" and "some more...", and 8 divs of "fourth test" and "even more...". What am I missing?

This is the what is stored in the message object

message = [{"date": "Sat, 15 Oct 2016 14:47:00 GMT", "id": 5, "post": "test message for the body of the post", "title": "first note"},
{"date": "Sat, 15 Oct 2016 15:20:06 GMT", "id": 6, "post": "some more text for a new test post", "title": "second test"},
{"date": "Mon, 17 Oct 2016 13:24:05 GMT", "id": 7, "post": "some more text", "title": "third test"},
{"date": "Mon, 17 Oct 2016 13:28:09 GMT", "id": 8, "post": "even more text to add", "title": "fourth test"}]


This is from userhome.js

else {
var noteObj = JSON.parse(message);
var note = null;

$.each(noteObj, function (index, value) {
note = $(".list-group").clone();
$(note).find("h4").text(value.title);
$(note).find("p").text(value.post);
$(".jumbotron").append(note);
});

$(".list-group:first").empty();

//print success message to console
console.log("successfully retrieved notes");
}


This is from userhome.html

<div class="jumbotron">
<h1>welcome!</h1>
<div class="list-group">
<a href="#" class="list-group-item active">
<!--start dynamic section-->
<h4 class="list-group-item-heading"></h4>
<p class="list-group-item-text"></p>
<!--end dynamic section-->
</a>
</div>
</div>

Answer

When you call $(".list-group").clone(), you are cloning the entire list on each iteration. Therefore, you get 1 clone on the first iteration, 2 clones on the second iteration, 4 clones on the third iteration, etc. You then change the title and post of all of the clones, and then add all of the clones to jumbotron. So be more specific with your selection. For example, you could use $(".list-group").first().clone().

Comments