How to refer to a dynamically added element after loading the DOM without having to act on any events?

I know there are .on and .live (deprecated) available from JQuery, but it is assumed that you want to attach event handlers to one or more events of a dynamically added element that I don’t have. I just need to reference it so that I can access some of its attributes.

And, more specifically, there are many dynamic elements, such as everything, with a set of class="cluster" and each with a different value for the title attribute, top attribute and left attribute.

None of these jquery options work:

 var allClusters = $('.cluster'); var allClusters2 = $('#map').children('.cluster'); var allClusters3 = $('#map').find('.cluster'); 

Again, I don't want to attach any event handlers, so .on doesn't seem to be the right solution, even if I have to capture it, add a dummy event, doNothing handler, and then just specify my attributes.
There must be a better solution. Any ideas?

UPDATE:
I didn’t formulate the title correctly, because I wanted to say that the elements were dynamically added to the DOM, but not through jQuery. Title updated.

+4
source share
2 answers

I get it. Elements were not displayed because the DOM has not yet been updated .

I work with Google Maps and MarkerClustererPlus to give more context, and when I add map markers using markerclustererplus, they were not available in javascript code after adding.

Adding google maps event listener to my google map fixes the problem:

 google.maps.event.addListener(myMarkerClusterer, 'clusteringend', function () { // access newly added DOM elements here }); 

As soon as I add this listener, all of the above jQuery selectors and / or methods work fine:

 var allClusters = $('.cluster'); var allClusters3 = $('#map').find('.cluster'); 

Although this was not, but this is because it finds only the direct decoders of the parent:

 var allClusters2 = $('#map').children('.cluster'); 
+2
source

Do what you need to do in the ajax callback:

 $.ajax(...).done(function (html) { //append here allClusters = $('.cluster'); }); 

If you want them separate, you can always bind handlers after the fact or use $.when :

 jqxhr = $.ajax(...).done(function (html) { /* append html */ }); jqxhr.done(function () { allClusters = $('.cluster') }); $.when(jqxhr).done(function () { /* you get it */ }); 

If they are added without ajax changes, just move the cluster -finding code wherever the DOM changes happen.

If this is not an option, then I think you just need to check the interval.

+1
source

All Articles