简体   繁体   中英

Select DOM elements in jQuery - Dynamically Added

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.

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.

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.

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.

I know this post is old but I believe this can be done using the jQuery find method.

http://jsfiddle.net/vreTG/1/

// 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");

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