Nowadays I am working on an application. I been struggling for a while how I should select a parent of a child.
What I trying to do is Click on child(card) and do something with a parent(cell).
Is there a way how I could querySelector the parent e.g.
const selectedParentFromChild = document.querySelector(".child .parent")
Solution:
For those which were struggled as well. You can use parentElement like @Phix has mentioned down below in the comments.
You have 2 ways to do that:
you can use the Element.parentElement, it's return the parent element.
you can use Element.closest(). According to MDN:
The
closest()method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
const child = document.querySelector(".child");
const parentMatched = child.closest(".parent-matched");
try this:
let child = document.querySelector(".child");
let parent = child.parentNode;
and you can't get the parent of a child via css only, there is currently no such selector see here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With