Irsyad14 Irsyad14 - 1 year ago 89
jQuery Question

jQuery append inside for loop

I have a particular problem which I dont seem to wrap around my head. I am using reddit api to get the data.


$(function() {

console.log("is it loading")

var q;
for(var i = 2; i <; i++){
q =[i];
$('#main').append('<h4>' + + '</h4><br><button class="btn btn-success trigger">answer</button><div class="answer">'+ +'</div>')


console.log("clicked", [i]);
console.log("error occured")

So basically I wanted to show the answer using #trigger. But the problem lies when I clicked the #trigger button, the array shows 27 count rather than the actual count which is 26. It somehow added one count when I click #trigger button. Right now I cannot managed to click the button to show the answer. Any help would be much appreciated

Answer Source

Try this and see. It's not doing lookups. It's using/bind on the elements as it makes them. A better approach might be to use a delegated listener with contextual lookups.

        .then(function(data) {
            var $main = $('#main');

            //use slice so you can use forEach instead of rolling your own for loop
                //instead of looking up trigger, create it so you can do whatever you want with it
                var $trigger = $('<button class="btn btn-success">answer</button>');
                //same with answer
                var $answer = $('<div class="answer">'+ +'</div>');


                $trigger.on('click', function(e){

                    .append('<h4>'+ +'</h4><br>')
        }).catch(function(error) {
            console.log("error occured")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download