JQuery - append in element generated by prepend in a each

1

How do I add elements to an element that was added within an each? Here's an 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 fine but apparently the append does not work because I do not find the id added in the prepend.

    
asked by anonymous 27.07.2016 / 20:13

1 answer

0

You could do 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
  }
});

Only one thing, if you want to capture the current element inside the loop , you must use, instead of data.id , the item itself passed as argument. It would look 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 do not know if this is what you want, but it stays there if it is.

    
27.07.2016 / 20:22