skip to Main Content

I am using MutationObserver to listen for any element added in the dom. After the element(s) is added, I want to check whether the element(s) had the computer style cursor to be pointer or not. But I am not sure how to approach this problem as it returns the parent node added in the dom, it didn’t query each child of the parent node :-

function myfunc() {
    const ele = document.createElement('div')
  ele.innerHTML = `<span><a>I am added</a></span><h2><a>I am two</a></h2>`
  
  document.body.appendChild(ele)
}

const observer = new MutationObserver(mutationsList => {
  mutationsList.forEach(mutation => {
    // Check if nodes were added
    if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
      // Iterate over added nodes
      mutation.addedNodes.forEach(addedNode => {
        // Check if added node is an element and not a script
        if (
          addedNode.nodeType === Node.ELEMENT_NODE &&
          addedNode.tagName !== 'SCRIPT'
        ) {

          const child = addedNode.childNodes;
          if(child.length > 0) {
            for (let i = 0; i < child.length; i++) {
              console.log(child[i])
                if(window.getComputedStyle(child[i]).cursor === 'pointer') {
                console.log('This')
              }
                else {
                    console.log('No It didn')
                }
            }
          }
        }
      });
    }
  });
});

observer.observe(document.body, { childList: true, subtree: true });
a {
  cursor: pointer;
}
<button onClick="myfunc()">
Add to DOM
</button>

2

Answers


  1. First of all, I’d start by using a dedicated container div to push elements into instead of the body of the document.

    Next you dont have to work with child list and instead (since you only add elements) can simply get the latest element added to the container (or body). Afterwards you get all anchor elements of that element by using lastElementChild. Now iterate over each anchor tag and compare the computed style with what you want.

    function myfunc() {
      const ele = document.createElement('div');
      ele.innerHTML = `<span><a>I am added</a></span><h2><a>I am two</a></h2>`;
      const elem = document.getElementById("container");
      elem.appendChild(ele);
      i++;
    }
    
    let i = 0; //specify a value to distinguish each span
    const targetNode = document.getElementById("container");
    const config = {
      attributes: true,
      childList: true,
      subtree: true
    };
    
    const callback = (mutationList, observer) => {
      for (const mutation of mutationList) {
        if (mutation.type === "childList") {
          console.log("A child node has been added or removed.");
          const container = document.getElementById("container");
          let lastElement = container.lastElementChild;
          var a = lastElement.getElementsByTagName('a');
          for (let j = 0; j < a.length; j++) {
            var elem = a[j];
            const compStyles = window.getComputedStyle(elem).cursor;
            if(compStyles == 'pointer')
            {
              console.log("Works!");
            }
          }
        }
      }
    };
    
    // Create an observer instance linked to the callback function
    const observer = new MutationObserver(callback);
    
    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);
    a {
      cursor: pointer;
    }
    <button onClick="myfunc()">
    Add to DOM
    </button>
    
    <div id="container">
    
    </div>
    Login or Signup to reply.
  2. The code you provided demonstrates the use of a MutationObserver to detect changes in the DOM, specifically when nodes are added. It then iterates over the added nodes and checks if any of the child nodes have a CSS style of cursor: pointer.

    To get the specific CSS-styled element from the entire node, you can modify the code as follows:

    const observer = new MutationObserver(mutationsList => {
      mutationsList.forEach(mutation => {
        // Check if nodes were added
        if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
          // Iterate over added nodes
          mutation.addedNodes.forEach(addedNode => {
            // Check if added node is an element and not a script
            if (
              addedNode.nodeType === Node.ELEMENT_NODE &&
              addedNode.tagName !== 'SCRIPT'
            ) {
              const elementsWithPointerCursor = Array.from(
                addedNode.querySelectorAll('*')
              ).filter(element => {
                const computedStyle = getComputedStyle(element);
                return computedStyle.cursor === 'pointer';
              });
    
              if (elementsWithPointerCursor.length > 0) {
                console.log('Elements with pointer cursor:', elementsWithPointerCursor);
              } else {
                console.log('No elements with pointer cursor found.');
              }
            }
          });
        }
      });
    });
    
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });

    In the updated code, after determining that the added node is an element, it uses querySelectorAll(‘*’) to select all descendant elements within that node. Then, it filters those elements based on their computed style, specifically checking if the cursor property is set to pointer. The resulting array contains the elements with a pointer cursor.

    Note: This code will find all elements with a pointer cursor within the added node and its descendants. If you only want to check the added node itself, you can remove the querySelectorAll(‘*’) and replace addedNode with addedNode in the filtering step.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search