Reputation: 36937
Is there anyway to listen for elements adding themselves to the DOM after load? Currently I have a bunch of tables using DataTables and I have a bunch of other elements that I would like to manipulate when and if the type of element I am looking for is found to have "appeared" on the page. Seeing as what I am attempting to do only works on elements currently on the page when loaded but not after they load such is the case with many elements currently in play.
Ultimately I am currently looking for a means of avoiding going back through the entire code base just to make something happen only if something is found on the page, but after its loaded.
Upvotes: 0
Views: 780
Reputation: 179066
There's no "element added to dom" sort of event that's cross-browser compatible, and the ones that exist for specific browsers are generally discouraged as they tend to cause more issues than they solve.
Usually the issue with elements not existing in the DOM is that they miss event-binding. jQuery has awesome event-delegation that can be used to bind events to a container so that when an event bubbles up to the container, the callback is fired in the context of the element that received the event.
For example, you could bind events using:
$('a').click(doStuff);
but that would not work for any new links, instead you could use something like:
$('#some-container').on('click', 'a', doStuff);
which would intercept all click events on all links in the #some-container
element, regardless of when they were added to the page.
Upvotes: 2