javascripthtmldombookmarklethighlight

highlight a DOM element on mouse over, like inspect does


We have a bookmarklet, and the user clicks a button and an inspect like highligther needs to kick in. We want to this to be cross browser.

For this we need to detect the DOM element during the mouse move, and once we have this element we need to highlight with CSS.

We have problems detecting the DOM element by mouse move, can you guide us how this is done?

Once we have this DOM element, on user click we need to extract XPath.


Solution

  • You can hook mousemove on document or document.body, then use the target property of the event object to find out the topmost element the mouse is over. Then applying CSS to it is probably most easily done by adding a class to it.

    It's tempting to think the :hover psuedo-class could do it without JavaScript, but I'm struggling to see how to apply it only to the "deepest" hovered element (for instance, in <p>x<em>y</em>z</p>, only to the em and not the p).

    Here's an example using JavaScript (not :hover):

    let prev = null;
    
    document.body.addEventListener(
        "mouseover",
        (event) => {
            if (event.target === document.body || (prev && prev === event.target)) {
                return;
            }
            if (prev) {
                prev.classList.remove("highlight");
                prev = null;
            }
            if (event.target) {
                prev = event.target;
                prev.classList.add("highlight");
            }
        },
        false
    );
    .highlight {
        background-color: yellow;
    }
    <p>I'm a paragraph, with <strong>some strong text</strong>, and some <em>emphasized text</em>.</p>
    <p>I'm another paragraph.</p>
    <div>Here's a div</div>