Tsuneo Yoshioka
Tsuneo Yoshioka

Reputation: 7874

Change dynamically created element

I'm building browser plugin (safari extension) that automatically changes an element (by "prepend"). It can be done by calling prepend like:

$(document).ready(function(){
  $("a").prepend("<img ...>").
})

But, how can I change elements that are created dynamically using javascript?

Upvotes: 0

Views: 142

Answers (4)

user632287
user632287

Reputation:

You can store the object you create in a global variable so it is available throughout your webpage... Like so:

var img;
$(document).ready(function(){
    img = $("<img ...>");
    $("a").prepend(img).
});

Then later on in some other function or something...

$(img).click(function() { 
     // blah
});

Upvotes: 0

qwertynl
qwertynl

Reputation: 3933

You can 1st create the object:

$(document).ready(function(){
    var img = $("<img ...>");
    $("a").prepend(img);
    // do something with img
});

Upvotes: 1

putvande
putvande

Reputation: 15213

You could listen for DOM change:

$("body").on("DOMSubtreeModified", function(){
    alert('DOM changed');
});

And than figure out what has changed. But that isn't clear from your question what you would like to do.

Upvotes: 1

ridvanzoro
ridvanzoro

Reputation: 646

You can create trigger,

    $(document).ready(function(){
      $("a").prepend("<img id="imgId"...>").
        $(document).trigger('asd');
    })
$(document).on('asd', function() {

  });

Or you can create event listner

$(document).ready(function(){
          $("a").prepend("<img id="imgId"...>").

})
$(document).on('click','imgId',function(){

 });

Upvotes: -1

Related Questions