Search code examples
javascriptmutation-observers

How can I wait for nextElementSibling to exist then execute my function on on it?


I want to execute a function when the nextElementSibling exists for a given node.

So in my dom I have nodes a and b.

<section>
   <div id="a">...</div>
   <div id="b">...</div>
</section>

I have a third-party script that is dynamically injecting new div nodes into a node at an unknown future time.

<section>
   <div id="a">...</div>
   <div id="b">...</div>
   <div id="c">...</div>
   <div id="d">...</div>
</section>

I can target element b and perform a function with it. I want that function to say "when my node 'b' has a nextElementSibling, call function X with that node ('c').

I really want to say 'When element b exists, execute function X(a)', 'When element c exists, execute function X(b)', 'When element d exists, execute function X(c)'.


I found a function for waiting for an element to exist based on its selector.

function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                resolve(document.querySelector(selector));
                observer.disconnect();
            }
        });

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

However this requires a selector to work but there isn't a selector for "my next sibling". Could it work somehow to detect the next element sibling existing?


Solution

  • Thanks to @Bergi for pointing me in the right direction. I was over thinking it and trying to use a selector.

    function waitForNextSibling(me) {
      return new Promise(resolve => {
        if (me.nextElementSibling) {
            return resolve(me.nextElementSibling);
        }
    
        const observer = new MutationObserver(mutations => {
            if (me.nextElementSibling) {
                resolve(me.nextElementSibling);
                observer.disconnect();
            }
        });
    
        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
      });
    }
    

    usage

    waitForNextSibling(me).then((next) => {
    
    })