0

I want to observer a deeply nested element (textarea in this example), but the following code does not work.

can anyone help me out?

<div id="parent" style="width:500px;height:200px;" class="parent mother">

</div>
<button id="button" style="width:200px;height:60px;" class="button btn"></button>
<script>
    button = document.getElementById("button");
    const observer = new MutationObserver(function(mutations_list) {
        mutations_list.forEach(function(mutation) {
            mutation.addedNodes.forEach(function(added_node) {
                if (added_node.className == 's-JGcg fFOiLQ JhFYDw T9BsEA _01h2nw') {
                    //if (added_node.id == 'child') {
                    console.log(`${added_node}has been added`);

                    observer.disconnect();
                }
            });
        });
    });

    observer.observe(document.querySelector("body"), {
        subtree: true,
        childList: true,
    });

    button.addEventListener("click", fn);

    function fn() {
        document.querySelector("#parent").innerHTML = `<div><div><div>
            <textarea class="s-JGcg fFOiLQ JhFYDw T9BsEA _01h2nw" placeholder="What happens" rows="5"></textarea>
            </div></div></div>`;
    }
</script>
Jimmy Xee
  • 27
  • 5
  • addedNodes doesn't list child nodes. You need to also use querySelector on each node. – wOxxOm Apr 25 '22 at 14:56
  • @wOxxOm So if addedNodes does not work with child nodes, what should we do if the target element is deeply nested like buried under 30 divs? – Jimmy Xee Apr 25 '22 at 23:57
  • Use querySelector. – wOxxOm Apr 26 '22 at 00:05
  • @wOxxOm I know querySelector works, but my problems is that querySelector will not monitor the DOM change. I need mutationobserver to observe the DOM changes to triger my next function. – Jimmy Xee Apr 26 '22 at 00:11
  • It'll work if you use it on each node, [example](https://stackoverflow.com/a/32537455). – wOxxOm Apr 26 '22 at 00:43

0 Answers0