Detect every element on webpage with mouse

Viewed 305

I am developing a chrome extension and a certain feature allows the user to click on a button to select an element on the current page (just like the hover feature in Dev Tools). A certain problem I am encountering is when some elements (children) within a large div are not being singled out. Is there a way to get the last child of where the mouse is currently pointing?

Note: lastChild does not work as it will get me the last child of the outermost parent div.

Here is the flow:

popup.js

let selectElem = document.getElementById('select_element_button');
  selectElem.addEventListener("click", function(){
    chrome.runtime.sendMessage("hello");
  });

background.js

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    console.log(message + "from bg");
    if(message == "hello"){
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.sendMessage(tabs[0].id,"toContent");  
        });
    }
});

content.js

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
    if(message == "toContent"){
        document.addEventListener("mouseover", (event) => {
            event.target.style.backgroundColor = "rgba(121, 204, 255, 0.4)";
        });
        document.addEventListener("mouseout", (out) => {
            out.target.style.backgroundColor = "";
        });
    }
});
1 Answers

Edit: condition on styling target if not containing an element node:

document.addEventListener("mouseover", (event) => {
    var el = event.target;
    var hasChildElement = false;
    if (el.hasChildNodes()) {
        for (var i = 0, j = el.childNodes.length; i < j; i++) {
            if (el.childNodes[i].nodeType === 1) {
              hasChildElement = true;
              break;
            }
        }
    }
    if (!hasChildElement) {
        el.style.backgroundColor = "rgba(121, 204, 255, 0.4)";
    }
});

More on node types here: https://developer.mozilla.org/fr/docs/Web/API/Node/nodeType

Related