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. // jQuery
  2. var parentElement = $('#childElement').parent();
  3.  
  4. // VANILLA JAVASCRIPT
  5. // Get just the parent.
  6. const parentElement = document.querySelector('#childElement').parentElement;
  7. // Go up the chain until a class is found, not found returns null.
  8. const parentElement = document.querySelector('#childElement').closest('.parentClass');
Programming Language: Javascript