14 May 2023

To use these, you first need to get a reference to the child element whose parent you want to get. You can use a method such as getElementById(), querySelector(), or getElementsByClassName() to get a reference to the child element. Once you have a reference to the child element, you can use the parentElement property to get a reference to its parent element. This property returns the parent node of the child element. If you want to get the parent element of an element based on a specific CSS selector, you can use the closest() method. This method searches up the DOM tree from the current element until it finds an element that matches the specified selector. The closest() method returns null if no matching ancestor element is found.

Source code viewer
  1. // Get just the parent.
  2. const parentElement = childElement.parentElement;
  3. // Go up the chain until a class is found, not found returns null.
  4. const parentElement = childElement.closest('.parentClass');
Programming Language: Javascript