1

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.

Valdemar Vreeman
  • 177
  • 2
  • 16

2 Answers2

6

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");
Oleg Barabanov
  • 2,468
  • 2
  • 8
  • 17
David Almeida
  • 61
  • 1
  • 2
4

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

Ben.S
  • 708
  • 1
  • 5
  • 24
  • `.child` is not an id, but a class. The same with `querySelector` instead of `getElementById` should work. There is also a typo, the last char should be `;`instead of `,`. – Marc Compte Jun 03 '21 at 21:50
  • No problem, the idea was right, just some small corrections. Also, this may be of interest here: https://stackoverflow.com/a/8685780/4477659 – Marc Compte Jun 03 '21 at 21:54
  • Which is better to use parentNode or parentElement I been searching on the caniuse.com website and there I saw that the parentNode is more compatible then the parentElement, but the parentNode has more errors. – Valdemar Vreeman Jun 03 '21 at 22:04
  • @ValdemarVreeman for the most cases there are the same, see here for differences https://www.geeksforgeeks.org/difference-between-dom-parentnode-and-parentelement-in-javascript/ – Ben.S Jun 03 '21 at 22:11
  • @ValdemarVreeman can you please check my answer, if it is for you, thanks – Ben.S Jun 04 '21 at 12:28