Is there a way in Javascript or jQuery to find out when a HTML element has been added to the DOM dynamically, either through jQuery.append()
or one of the native Javascript's node manipulators? There are probably several different ways to add HTML elements to the page dynamically, so I'm not sure what event or events I should be listening on.
The specific example is that that an anchor tag is being added to the page by a third-party Javascript code (that I cannot modify or easily glean). I want to change the link's text.
I am hoping there is something better than a setTimeout()
loop on $(SOME ELEMENT).length > 0
. (part of which I saw in How can I determine if a dynamically-created DOM element has been added to the DOM? but it's from 2008)
To check if an element is connected or attached to the DOM or the document object ( or otherwise called the context ), you can use the isConnected property in the element's object in JavaScript. The isConnected element property returns boolean true if it connected to the DOM ( document object) and false if not.
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.
You can use Mutation Observers for this purpose - at least if you do not need to support IE/Opera.
Here's a short example (taken from html5rocks.com) on how they are used:
var insertedNodes = []; var observer = new WebKitMutationObserver(function(mutations) { mutations.forEach(function(mutation) { for(var i = 0; i < mutation.addedNodes.length; i++) insertedNodes.push(mutation.addedNodes[i]); }) }); observer.observe(document, { childList: true }); console.log(insertedNodes);
Note the Webkit
prefix. You need to use the browser-specific prefix. In Firefox it would be Moz
instead.
Based on the technique by Daniel Buchner I have created a small library to catch DOM insertions. It's more comfortable to use than the hack itself.
It uses css animation events, so it's not based on DOMMutationEvents, and it's not Mutation Observer. So it's not slowing down the page and it has a wider support than MutationObserver.
It has an added benefit of being able to use any CSS selectors you want.
Example usage:
insertionQ('.content div').every(function(element){ //callback on every new div element inside .content });
If you invoke it after DOMReady, it's going to catch only new elements.
See https://github.com/naugtur/insertionQuery for more options
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With