Skip to content

Instantly share code, notes, and snippets.

@Hampei
Last active December 29, 2015 05:19
Show Gist options
  • Save Hampei/7620643 to your computer and use it in GitHub Desktop.
Save Hampei/7620643 to your computer and use it in GitHub Desktop.
// browser support: chrome, safari, firefox, opera, ie9+, ieMobile10+ (Opera Mini not supported)
// No external libraries needed.
// calls fn on all current and future elements matching selector within the first element matching container_selector.
// find_with_mutations('.container', '.element', function(el) { })
window.find_with_mutations = function(container_selector, selector, fn) {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
[].slice.call(mutation.addedNodes).forEach(function(el) {
if (el.nodeType !== 1) return;
if (matchesSelector(el, selector)) // Node itself matches
fn(el);
[].slice.call(el.querySelectorAll(selector)).forEach(function(el2) { // subnodes match
fn(el2);
})
})
});
});
var target = document.querySelector(container_selector);
[].slice.call(target.querySelectorAll(selector)).forEach(function(el) { // handle existing elements
fn(el)
})
observer.observe(target, { childList: true, subtree: true }); // handle future elements
}
// crossbrowser matchesSelector.
window.matchesSelector = function(element, selector) {
ms = element.matchesSelector || element.webkitMatchesSelector ||
element.mozMatchesSelector || element.oMatchesSelector || element.msMatchesSelector;
if (ms) return ms.call(element, selector)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment