Jquery - append in prepend generated element in each

Asked

Viewed 160 times

1

How do I add elements to an element that has been added inside a each ? Following example:

            $.each(data.id, function(i, item) {
                $( ".lado" ).prepend("<div id='tes'>" + data.id + "</div>");

                if (data.id == i) {
                    $( "#tes" ).append("<div>" + data.id + "</div>");
                }

            });

The prepend works but apparently the append doesn’t work because I don’t find the id added in the prepend.

1 answer

0

You could do it like this:

$.each(data.id, function(i, item) {
  var tes = $("<div id='tes'>" + data.id + "</div>");// guarda o novo elemento dentro de uma var
  $(".lado").prepend(tes); // usar o novo element
  if (data.id == i) {
    tes.append("<div>" + data.id + "</div>"); // já está disponível para appends
  }
});

Just one thing, in case you want to capture the current element inside the loop, should use instead of data.id, own item passed as argument. In case would be like this:

$.each(data.id, function(i, item) {
  var tes = $("<div id='tes'>" + item + "</div>"); // guarda o novo elemento dentro de uma var
  $(".lado").prepend(tes); // usar o novo element
  if (item == i) {
    tes.append("<div>" + item + "</div>"); // já está disponível para appends
  }
});

I don’t know if that’s what you want, but stay there if it is.

  • You’re right what you did, but since he generated the code, you have to work with the $.(document), otherwise you won’t find the positions.

  • @Williamaparecidobrandino, look at this fiddle and Inspecione the elements: https://jsfiddle.net/8p788u6w/1/ . As the new element is in the variable, the positions are found. That’s what I was talking about?

  • In this example, the id is the same for everyone, the result would be made up.

  • @Williamasimiliar, is an example rsrs. I put three ids equal to index of the loop to show the effectiveness of the append. But anyway, let’s wait for the AP to return to see if it served him. If you think something is really wrong could be more specific?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.