Home > Back-end >  Attribute selector does not take into account the elements contained in it
Attribute selector does not take into account the elements contained in it

Time:02-20

I have a line of HTML code:

<a href="/posts"  data-link><i ></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?

CodePudding user response:

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"  data-link><i >Nested element</i> <span>Another Nested element</span> Link tag itself</a>

  • Related