Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to detect all links within a div, on mouseover

In a Svelte app I’m trying to detect when the user is hovering over a link, within a div. I’ve added a mouseover event listener to the div, and am checking if the element is a link, but this is too simplistic: it doesn’t detect links that contain HTML tags.

Example code, also available as REPL:

<script>
    import { onMount } from 'svelte';
    
    let container;
    
    onMount(() => {
    container.addEventListener('mouseover', async (event) => {
            if (event.target.tagName !== 'A') return;
            console.log(event.target.attributes['href'].value);
        });
    });
</script>

<div bind:this={container}>
    <a href="https://www.example.com">Hello World</a>
    <a href="https://www.example.com"><strong>Hello World</strong></a>
</div>

The problem is that second link: hovering over it the target is the strong tag, not the a tag. So, how can I reliably detect all links within the container div, without having to add an event listener to every individual link?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

From the target, use .closest('a') to navigate to the enclosing <a> element, if any. (If the element that the event was dispatched to is an <a>, it’ll be returned.)

container.addEventListener('mouseover', (event) => {
    const a = event.target.closest('a');
    if (a) console.log(a.href);
});
container.addEventListener('mouseover', (event) => {
  const a = event.target.closest('a');
  if (a) console.log(a.href);
});
<div id="container">
  <a href="https://www.example.com">Hello World</a>
  <a href="https://www.example.com"><strong>Hello World</strong></a>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading