javascriptgoogle-chrome-extensionmutation-observers

Javascript mutation observer adressing an element within a <li>


Im using a mutation observer to observe the changes that happen to an <ul> element. when observing, i get the following output:

<li class="rt__body-row full flex gc-07 rt__body-row--odd">
<span class="rt__row-left short">48,359.50</span>
<span class="rt__row-center">0.063</span>
<span class="rt__row-right">01:57:44</span>
</li>

Now i want to write an if statement about the second spans text (0.063). How do I adress the second span in javascript? Im pretty new to programming and below is my code:

function obser1() {
    const trades = document.querySelector('.scrollbar-dark');
    const observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            
            if (mutation.addedNodes.length) {
                console.log(mutation.addedNodes[0]);
            }
        })
    });
    console.log("obs1");
    observer.observe(trades, {
        childList: true,
        subtree: true,
        attributes: true,
        characterData: true
    })
    console.log("observed");
}

window.setTimeout(obser1, 1700);

Below is my manifest file:

  "name": "Bybit orderbook color",
  "version": "1.1",
  "manifest_version": 2,

  "content_scripts": [
    {
      "matches": [ "https://www.bybit.com/trade/usdt/BTCUSDT" ],
      "css": [ "Style.css" ],
      "run_at": "document_idle",
      "js": [ "background.js" ]

    }

  ],

  "permissions": [ "activeTab" ]


}

Solution

  • Assuming mutation.addedNodes[0] is an html collection, you could do

    const vals = [...mutation.addedNodes[0].querySelectorAll("span")].map(span => span.textContent);
    

    If a string you can do

    const fragment = document.createElement("div");
    fragment.innerHMTL = mutation.addedNodes[0];
    const vals = [...fragment.querySelectorAll("span")].map(span => span.textContent);