javascripthtmlcssweb-inspector

Simulate Inspect Element tool with JS


I am attempting to make an inspect element-like tool using JS. In most browser's inspect tools you are able to hover over elements on the page and click them to show where they are in the website's code. The only way I can think of simulating this is to add event listeners to every element on the page. I feel that this is bad for a lot of reasons. Is there any other way I can do this? If not, would adding event listeners to every element on the page be a good idea?


Solution

  • You can use Javascript's elementFromPoint() method to get the Element on which the cursor is present, by using mouse events to get the coordinates of the cursor.

    Here's a code example:

    function highlighter() {
    
    
        function getElementOnCoordinates(x, y) {
            return document.elementFromPoint(x, y)
        }
    
        let currentElement;
        window.addEventListener('mouseover', (event) => {
    
    
            if (currentElement) {
                currentElement.classList.remove('bordered')
            }
    
            let [x, y] = [event.clientX, event.clientY]
            currentElement = getElementOnCoordinates(x, y);
    
            currentElement.classList.add('bordered')
        });
    }
    

    As you can see, I have used the mouseover event on the window to get the coordinates of the cursor, and then using those x & y values I get the Element present on that location. Then I add a CSS Class which gives that element an outline.

    There is also a condition that checks if there is already an element and removes the styling from it in order to remove that outline when coordinates change.