Search code examples
javascripthtmljquerydomselectors-api

Exclude sub DIV from Javascript & DOM


I have two div. <div class="card" id="openWebsite"> and sub div <div class="card__btn">

If someone clicks on my root div they will get redirected to example.com and when someone clicks sub div they are redirected to example.com & example.net, they are getting redirected two both links in two new tab.

I want, if someone clicks on root div they should get redirected to example.com and when someone clicks on sub div button they should only be redirected to example.net not example.com

how to exclude sub div <div class="card__btn"> from javascript.

Code :

const webPage = document.querySelectorAll("#openWebsite");
webPage.forEach((e) => {
  e.addEventListener("click", () => {
    const site = e.getAttribute("data-site");
    window.open(site, "_blank") || window.location.replace(site);
  });
});
.card {

background: blue;
height: 50px;
width: 500px;

}
<div class="card" id="openWebsite" data-site="https://example.com">
    <div class="card__btn">
      <a href="https://example.net">
        Visit Site
      </a>
    </div>
  </div>

Already tried from jQuery exclude elements with certain class in selector , https://api.jquery.com/not/ , document.querySelector exclude part of DOM, https://www.w3schools.com/jsref/met_document_queryselectorall.asp

document.querySelectorAll("#openWebsite").not(".card__btn");

and

document.querySelectorAll(".card").not(".card__btn");

and

document.querySelectorAll("#openWebsite:not('.card__btn')");

Solution

  • This will work!!

    <script>
    const webPage = document.querySelectorAll("#openWebsite");
    webPage.forEach((e) => {
        e.addEventListener("click", (data) => {
            if (data.target !== e.querySelector("a")) {
                const site = e.getAttribute("data-site");
                window.open(site, "_blank") || window.location.replace(site);
            }
        });
    });
    </script>