-2

I have a div with such content:

<div class="foobar">Red</div>
<div class="foobar">Yellow</div>
<div class="foobar">Cyan</div>
<div class="foobar">Luke Skywalker</div>
<div id="data"></div>

I use this jQuery function to replace text inside the divs. After all I append 2 more .foobar divs to #data:

$(function() {
    $(".foobar").each(function() {
        $(this).html("Black");
    });
    appendDiv();
});

function appendDiv() {
    $("#data").append("<div class='foobar'>White</div>");
    $("#data").append("<div class='foobar'>Orange</div>");
}

And here I don't know how to apply inited .each function to appended divs. I've tried that, but it didn't worked for me:

$("#data").on("load", ".foobar", function(){
    $(this).html("Black");
});

How to apply .each function to appended html?

Scripy
  • 143
  • 13
  • 6 `.foobar` divs with "Black" expression in each of them – Scripy May 06 '17 at 20:01
  • @HenryDev and if I call `appendDiv` again, it should be 8 `.foobar` divs with "Black" in them – Scripy May 06 '17 at 20:02
  • if you append first then run for each you got 6 `.foobar` updated to `Black`? check my answer... – Dalin Huang May 06 '17 at 20:04
  • If you're appending the HTML why not just set the values to `Black` when you append? The question makes no sense. Also note that your `each()` loop is redundant. You can just do `$('.foobar').html('Black');` – Rory McCrossan May 06 '17 at 20:07

3 Answers3

1

function appendDiv() {
  $("#data").append("<div class='foobar'>White</div>");
  $("#data").append("<div class='foobar'>Orange</div>");
}


$("#data").on("click", function() {
  appendDiv();
  $(".foobar").each(function() {
    $(this).html("Black");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foobar">Red</div>
<div class="foobar">Yellow</div>
<div class="foobar">Cyan</div>
<div class="foobar">Luke Skywalker</div>
<div id="data">[TEST click me]</div>
Dalin Huang
  • 11,212
  • 5
  • 32
  • 49
0

Store the result $(".foobar") in a variable or, use this expression again.

Walle Cyril
  • 3,087
  • 4
  • 23
  • 55
  • I guess there's another way to solve it without storing data in variables, what if instead of one word I'm appending a lot of data and calling appendDiv many times? – Scripy May 06 '17 at 20:00
0

This should work,

$(".foobar").each(function(index, el) {
    $("#data").append($(el).clone());
    console.log($("#data").html());
});

Explanation: It loops through all the divs with class foobar and clones than append each to the data div.

Abhishek Sharma
  • 2,485
  • 1
  • 21
  • 35