I've got a button that I want to have enact changes to an element that is the sibling of the button's parent.
<div >
<div ></div>
<div >
<button>Click!</button>
</div>
</div>
I've tried playing around with event.target.closest
and similar, like so, but I cannot get it to work:
function clicks(event) {
const childElement = event.target.closest(".child");
const parentElement = childElement.target.closest(".parent");
const targetElement = parentElement.target.closest(".target");
targetElement.style.display = "none";
}
addEventListener('click', clicks);
CodePudding user response:
You can use the parentNode property to get the parent element of the button, and then use the nextElementSibling property to get the target element:
function clicks(event) {
const parentElement = event.target.parentNode;
const targetElement = parentElement.nextElementSibling;
targetElement.style.display = "none";
}
addEventListener('click', clicks);
CodePudding user response:
As stated in the comments section, you can't use .closest
as it moves up the DOM tree and you are trying to get a child of the parent in your final call to .closest
, one option is to use querySelector
on the parent element like so, also on your second line of function clicks
, the childElement
variable does not have
a target
property so it produces undefined
when setting parentElement
:
window.addEventListener("DOMContentLoaded", () => {
document.querySelector("button").addEventListener('click', clicks);
});
function clicks(event) {
const childElement = event.target.closest("div.child");
//const parentElement = childElement.target.closest(".parent");
const parentElement = childElement.closest("div.parent");
//Don't use .closest()
//const targetElement = parentElement.target.closest(".target");
const targetElement = parentElement.querySelector('div.target');
targetElement.style.display = "none";
//You could reduce all this to one line:
//event.target.closest('div.parent').querySelector('div.target').style.display = "none";
}
<div >
<div >I am the target</div>
<div >
<button>Click!</button>
</div>
</div>
Documentation: Element.closest
CodePudding user response:
You can use the two properties - parent and previousElementSibling for this.
This simple example finds the button's parent then finds the sibling that is just before it:
document.querySelector('button').addEventListener('click', function() {
event.target.parentElement.previousElementSibling.classList.add('nextClicked');
});
.nextClicked {
background-color: red;
}
<div >Parent
<div >Target</div>
<div >Child
<button>Click!</button>
</div>
</div>