简体   繁体   中英

jQuery without adding additional plugins: trigger event when an element with a specific class is added to the DOM

With jQuery: I want to listen for when an element with a specific class gets added to the page. When this event happens, I do some logic (represented by an alert message in this example).

 $('button').on('click', function(){ $(this).after('<p class="foobar">Element added</p>'); }); //Doesn't work, but shows what I am going after. I want to listen for when ap element with the class 'foobar' gets added to the DOM. When this happens: I want to be able to throw an alert. // $('p.foobar').on('when_it_is_added', function(){ // alert("I have been added to the dom"); // }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>click to add ap element </button> 

The key detail is that I need the event listener on this dynamic <p> element, and I need the event to fire once it is loaded in the DOM.

The fastest way to accomplish this is just by creating your own event and trigger it yourself after you append "p" element to the dom ... or simple execute another function after appended to dom .

Example 1 :

//Here I'm going to create an event 'tagAdded' and trigger it after appending element..

$('button').on('click', function(){
  $(this).after('<p class="foobar">Element added</p>').trigger('tagAdded');  
});

then

$('button').on('tagAdded', function(){

//do something

})

OR

Call method after append..

Example 2 :

$('button').on('click', function(){

  $(this).after('<p class="foobar">Element added</p>');

  someMethod();
});

function someMethod(){
var newPtAG = $('body').find('.foobar');

}

link: http://codepen.io/theConstructor/pen/GqpQqY

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM