Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

369
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

Instead of binding the container to a variable and setting the listener inside onMount you could also set it in Svelte directly on the element like this

<script>        
    function handleMouseover() {
        const a = event.target.closest('a')
        if(a) console.log(a.href);
    };
</script>

<div on:mouseover={handleMouseover}>
    <a href="/path">Hello World</a>
    <a href="https://www.example.com"><strong>Hello World</strong></a>
</div>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!