Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery live event for added dom elements

Tags:

I want to add a class to any DOM element that is on the page now or in the future that has a specified class and meets some criteria

so for some pseudo code

$('.location').live('load',function(){     if($(this).find('input:first').val().substr(0,1) == "!"){ $(this).addClass('hidden')} }); 

of course this does nothing

EDIT NOTE

this does not work either

$('.location').live('load',function(){     alert('adding location'); }); 
like image 440
mcgrailm Avatar asked Oct 01 '10 14:10

mcgrailm


People also ask

Which method is triggered when an element is added to the DOM?

We can detect if an element has been added to DOM using the MutationObserver object. This provides the ability to observe for changes being made to the DOM tree.

How do you bind change event in jQuery for dynamically added HTML element?

If you try to bind the elements that are dynamically added to the DOM using the click() method of jQuery, this will not work, because it only binds the click event to elements that exist at the time of the “binding”. To bind the click event to all existing and future elements, use jQuery's on() method.

How do I create a dynamic DOM element?

With document. createElement() method you can create a specified HTML element dynamically in JavaScript. After creation you can add attributes. If you want the element to show up in your document, you have to insert in into the DOM-tree of the document.


1 Answers

jQuery's live() feature is just subset of the livequery plugin, which is much richer. If you use livequery you could do something like..

$('.location').livequery(function() {    // perform selector on $(this) to apply class    }); 

That will cover existing elements plus any future elements added to the DOM.

like image 141
Gregg Avatar answered Nov 10 '22 01:11

Gregg