Reputation: 2352
In jQuery you could use .live()
, .on()
, and .delegate()
to bind events to DOM elements that have not been added yet on the page.
Is it possible to use a similar technique to select DOM elements not yet added to apply some functionality?
For instance, I want to select all input elements that have class .req and include a watermark called "Required".
Im already using a jquery plugin to do the watermark, but can't work on DOM elements added dynamically to the page.
Upvotes: 2
Views: 1867
Reputation: 45
I know this post is old but I believe this can be done using the jQuery find method.
// Generate some dynamic content
var dyn = '<ul>';
dyn += '<li class="req">Name</li>';
dyn += '<li class="req">Address</li>';
dyn += '<li class="opt">Phone Number</li>';
dyn += '<ul>';
// Add to DOM
$("#container").html(dyn);
// Find required fields
$("#container").find(".req")
.prepend("* ")
.css("color", "#900");
Upvotes: 0
Reputation: 25776
The answer is, it depends on how you are inserting elements into the DOM. If you are inserting them via jQuery then you could use a plugin such as livequery. As you can see, it hooks up to the core manipulation methods and anytime they are called it runs the callbacks registered on a live query. If you are inserting the elements via vanilla JS then as others have stated, the DOM muatation events are deprecated and unreliable hence polling would be your best option.
Upvotes: 0
Reputation: 39649
Unfortunately, no. Event delegation only works because you're technically binding to DOM nodes that are already present, so it doesn't matter that the elements that ultimately trigger the event don't exist yet. There are DOM-level 2 events on the way (and already implemented in some browsers) that will let you react to new DOM nodes being created or existing ones being manipulated, but until the browser support is better, there aren't really any options other than repeatedly polling the DOM for new nodes, which is horribly inefficient.
Upvotes: 1
Reputation: 150253
You can use mutation events(DOMNodeInserted
), but they are deprecated.
So unless you want to use them or pull the DOM every X time, the answer is NO
Pulling way:
setInterval(function(){
// Do what you want here.
$('.req').watermark("Required");
}, 500); // evey half a second.
Upvotes: 4