Created
August 5, 2018 16:14
-
-
Save dvlden/163acf4329a6812972086733e6784155 to your computer and use it in GitHub Desktop.
MutationObserver in JavaScript
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
/** | |
* Sometimes, an element that you might need to retrieve | |
* is not visible right away. It might be added later on | |
* via an asynchronous action. | |
* | |
* This is where MutationObserver in JS comes in | |
* and here you can learn from example. | |
* | |
* Example will retrieve video element from the web page. | |
*/ | |
function getVideoElement () { | |
return new Promise(resolve => { | |
let element = document.querySelector('video') | |
if (!element) { | |
let observer = new MutationObserver(observerCallback) | |
observer.observe(document.body, { | |
childList: true, | |
attributes: false, | |
subtree: true | |
}) | |
} | |
else { | |
console.log('Found the video element without Observer.') | |
resolve(element) | |
} | |
function observerCallback (mutations, observer) { | |
mutations.forEach(mutation => { | |
mutation.addedNodes.forEach(node => { | |
if (node.hasChildNodes()) { | |
let element = node.querySelector('video') | |
if (element) { | |
console.log('Found the video element through Observer, as a nested child.') | |
resolve(element) | |
observer.disconnect() | |
} | |
} | |
else { | |
if (node.nodeType === 1 && node.tagName.toLowerCase() === 'video') { | |
console.log('Found the video element through Observer, as a direct node.') | |
resolve(element) | |
observer.disconnect() | |
} | |
} | |
}) | |
}) | |
} | |
}) | |
} | |
getVideoElement().then(videoElement => { | |
// do something with it... | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment