Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference dynamically added element after DOM loaded without a need to act on any events?

I know there is .on and .live (deprecated) available from JQuery, but those assume you want to attach event handlers to one ore more events of the dynamically added element which I don't. I just need to reference it so I can access some of the attributes of it.

And to be more specific, there are multiple dynamic elements like this all with class="cluster" set 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 like the right solution even if I were to hijack it, add a bogus event, a doNothing handler, and then just reference my attributes.
There's got to be a better solution. Any ideas?

UPDATE:
I mis-stated the title as I meant to say that the elements were dynamically added to the DOM, but not through JQuery. Title updated.

like image 744
johntrepreneur Avatar asked Oct 21 '22 18:10

johntrepreneur


1 Answers

I figured it out. The elements weren't showing up because the DOM hadn't been updated yet.

I'm working with Google Maps and MarkerClustererPlus to give some more context, and when I add the map markers using markerclustererplus, they weren't available in the javascript code following the add.

Adding a google maps event listener to my google map fixed the problem:

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

Once I add that listener, all the above JQuery selectors and/or methods work just fine:

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

Although this one didn't, but that's because it only finds direct decendants of parent:

var allClusters2 = $('#map').children('.cluster');
like image 107
johntrepreneur Avatar answered Oct 24 '22 10:10

johntrepreneur