I have two div. <div id="openWebsite">
and sub div <div >
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 >
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: 100px;
width: 500px;
}
<div id="openWebsite" data-site="https://example.com">
<div >
<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')");
CodePudding user response:
You need to make you internal div position absolute then it will work the way you want.
CodePudding user response:
there your code is absolutely fine, just that you used
querySelectorAll()
instead of
querySelector()
only, because you only have one id on your page with the id "openWebsite",
below is a suggestion I believe you can add to your css to make your project more visible
.card {
background: blue;
height: 100px;
width: 500px;
}
.card__btn {
background-color: red;
padding: 10px;
}
a {
color: white;
}
CodePudding user response:
Events bubble up the dom. When you click on the anchor it opens example.net
.
Then it goes up the tree and your event handler is triggered, causing example.com
to be opened.
To stop this you can use Event.stopPropagation
. That way, the event won't continue going up the tree.
Because stackoverflow doesn't allow new tabs to be opened, I have also created a fiddle.
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);
});
});
document.querySelector(".card__btn").addEventListener("click", event => {
event.stopPropagation();
});
.card {
background: blue;
height: 100px;
width: 500px;
}
<div id="openWebsite" data-site="https://example.com">
<div >
<a href="https://example.net">
Visit Site
</a>
</div>
</div>