I am trying to run a content script (chrome extension) on a page. I managed to work jQuery, and I am trying to select an element document.ready().
However, as the page is a single-page-application, everything gets loaded dynamically, and it doesn't catch the element.
I believe I can achieve it with using setTimeout approach, however that doesn't sound right.
What is the right way of waiting for the element to be present, and when present get the element or run some code?
Edit: In order to simplify the problem, here is an example:
<body>
<div id="parent">
<button class="a b c">...</button>
</div>
</body>
Here, only body tag is created without any children, and then all the children get loaded into the body node dynamically as they are using Single-Page-Application approach (React to be specific).
MutationObserverAPI works as suggested in the comments, however it pulls all the changes and I couldn't figure out how to go through each MutationRecord object and detect if '.a.b.c'
class exists or not. Is there a way to only observe and wait for the '.a.b.c'
classed item exists, and when it does, get this element + triggering function.
This is the snippet I used for observing whole mutations:
MutationObserver = window.MutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
console.log(mutations);
});
observer.observe(document, {
subtree: true,
attributes: true,
childList: true,
characterData: true,
attributeOldValue: true,
characterDataOldValue: true
});
So where there is console.log
, I simply want to observe only the element with the related class name.