-1

I have dynamically created an element with the following class:

<span class="text">Hello</span>

and jQuery:

function changeText() {
   var oldText = $(this).text();
    $(this).text(oldText + " There");
}

$(function() {
    $(".text").each(function(){
        changeText.apply(this);
    })
})

Obviously, this is a simplified version of what is actually happening but the basics are there. Is it possible to apply this rule to dynamically created elements even though we are not using event listeners?

The problem here is that there is no specific location for these ".text" elements. The only place we know these will show up is in the body. I we use a mutationObserver on the body... wouldn't that be taxing performance?

Philll_t
  • 4,267
  • 5
  • 45
  • 59

2 Answers2

0

Like this

$dynamicElement.find(".text").each(function(){
    changeText.apply(this);
})
JoshKisb
  • 742
  • 7
  • 9
0

Do this instead:

function changeText() {
  var oldText = $(this).text();
  $(this).text(oldText + ' There');
}
$(function(){
$('.text').each(function(i, e){
  changeText.call(e);
});
});
StackSlave
  • 10,613
  • 2
  • 18
  • 35