In JavaScript, you can use the parentNode
property to get the parent element of a given element. Here’s an example:
var element = document.getElementById('myElement');
var parentElement = element.parentNode;
Note: the parentNode
property only returns the immediate parent element. If you want to access the ancestor elements, you can use a loop or recursion to traverse the DOM tree until you reach the desired ancestor.
You can also use other methods to get the parent element in JavaScript. Here are a few alternatives:
parentElement
property:
var element = document.getElementById('myElement');
var parentElement = element.parentElement;
Similar to parentNode
, the parentElement
property retrieves the immediate parent element of the given element.
closest
method:
var element = document.getElementById('myElement');
var parentElement = element.closest('.parent-class');
The closest
method returns the closest ancestor element that matches the specified CSS selector. In the example above, it selects the closest ancestor with the class name “parent-class”. You can use any valid CSS selector as an argument to closest
.
Traversing the DOM:
var element = document.getElementById('myElement');
var parentElement = element;
while (parentElement.parentNode) {
parentElement = parentElement.parentNode;
}
This method involves manually traversing the DOM tree by repeatedly accessing the parent node until you reach the topmost parent element. The parentNode
property is used in a loop until there are no more parent nodes.
JavaScript gets parent element example
Simple example code that demonstrates how to get the parent element in JavaScript:
<!DOCTYPE html>
<html>
<body>
<div id="parentElement">
<div id="childElement">Child Element</div>
</div>
<script>
var childElement = document.getElementById('childElement');
var parentElement = childElement.parentNode;
console.log(parentElement);
</script>
</body>
</html>
Output:
Using JavaScript, we select the child element using getElementById
and store it in the childElement
variable. Then, we retrieve the parent element using the parentNode
property and assign it to the parentElement
variable.
Finally, we log the parent element to the console using console.log(parentElement)
. If you run this code, you should see the parent element (<div id="parentElement">
) logged in the console.
Do comment if you have any doubts or suggestions on this Js code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version