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
- // Get just the parent.
- const parentElement = childElement.parentElement;
- // Go up the chain until a class is found, not found returns null.