In javascript, is it possible for me to return the element of any DOM element I'm hovering over?

Viewed 55

For example, if I have an HTML snippet like so:

<body>
    <div id="1">
        <span class="title">I'm a title!</span>
    </div>
    <div id="2">I'm the first element!</div>
    <div id="3">I'm the first element!</div>
<body>

Obviously, if I wanted to get a specific element, say the div with id of 1, I could do something like

document.getElementById("1").addEventListener("mouseover", () => console.log("in div 1!"), false);

and that would output in div 1! whenever I hovered over it. But is there some javascript I can have that apply to every single element in body? To basically write some function like, getElementUserIsHoveringOver()?

I don't think addEventListener works on HTMLCollections, which was my only idea.

1 Answers

mouseover bubbles, so if you attach a listener to the <body>, you can watch for events and log the event.target:

document.body.addEventListener('mouseover', (e) => {
  console.log(e.target);
});
<div id="1">
    <span class="title">I'm a title!</span>
</div>
<div id="2">I'm the first element!</div>
<div id="3">I'm the second element!</div>

Related