Created
May 3, 2019 10:15
-
-
Save mknospe/668767c0e30996f56496a4626fc8c18a to your computer and use it in GitHub Desktop.
ES5 Element ready observer using a MutationObserver to detect, if an HTML element generated on runtime is ready to be accessed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function isElement(addedNode, selector, callback) { | |
if (typeof addedNode.querySelector === 'function' && addedNode.querySelector(selector)) { | |
callback(); | |
} | |
} | |
var elementReadyObserver = new MutationObserver(function (mutations) { | |
for (var i=0, numMutations=mutations.length; i<numMutations; i++) { | |
for (var j=0, numNodes=mutations[i].addedNodes.length; j<numNodes; j++) { | |
isElement(mutations[i].addedNodes[j], '#YOUR-CSS-SELECTOR > .OF-THE-ELEMENT.TO-OBSERVE', function() { | |
elementReadyObserver.disconnect(); | |
// ... and do what you want to do with the element you've been observing | |
}); | |
} | |
} | |
}); | |
elementReadyObserver.observe(document.body, {attributes: true, subtree: true, childList: true}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment