Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelector child to parent

Tags:

javascript

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.


2 Answers

You have 2 ways to do that:

  1. you can use the Element.parentElement, it's return the parent element.

  2. 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");
like image 120
David Almeida Avatar answered Dec 07 '25 18:12

David Almeida


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

like image 29
Ben.S Avatar answered Dec 07 '25 19:12

Ben.S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!