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

117
Views
Attribute selector does not take into account the elements contained in it

I have a line of HTML code:

<a href="/posts" class="nav__link" data-link><i class="fa fa-file"></i><span>Pages</span></a>

and then I catch the event, cancel the transition by the link using my handler:

document.body.addEventListener("click", e => {
        if (e.target.matches("[data-link]")) {
            e.preventDefault();
            navigateTo(e.target.href);
        }
    });

As long as there is only text in the a tag, everything is fine, but as soon as nested span, i, and so on tags appear in it, this code does not work when you click on them.

How can I change this JS code so that it also applies to nested elements?

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

0

You might use .closest method:

document.body.addEventListener("click", e => {
  if (e.target.closest('a').matches("[data-link]")) {
    e.preventDefault();
    navigateTo(e.target.href);
  }
});

function navigateTo() {
  console.log("let's go!")
}
a,
a i,
a span {
  display: inline-block;
  padding: .5em;
  border: solid 1px
}
<a href="/posts" class="nav__link" data-link><i class="fa fa-file">Nested element</i> <span>Another Nested element</span> Link tag itself</a>

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!