0
0
JavascriptHow-ToBeginner · 3 min read

How to Select Parent Element in JavaScript: Simple Guide

In JavaScript, you can select a parent element of a given element using the parentElement property. This property returns the direct parent node of the element in the DOM tree.
📐

Syntax

The parentElement property is used on an element to get its immediate parent element in the DOM.

  • element.parentElement: Returns the parent element node or null if there is no parent.
javascript
const child = document.querySelector('selector');
const parent = child.parentElement;
💻

Example

This example shows how to select a child element and then get its parent element to change the parent's background color.

javascript
const child = document.querySelector('#child');
const parent = child.parentElement;
parent.style.backgroundColor = 'lightblue';
console.log('Parent tag name:', parent.tagName);
Output
Parent tag name: DIV
⚠️

Common Pitfalls

One common mistake is using parentNode expecting it to always return an element, but it can return other node types like Document or DocumentFragment. Also, parentElement returns null if the element has no parent element (like the root html element).

Always check if parentElement is not null before using it.

javascript
const child = document.querySelector('#child');
const parent = child.parentElement;
if (parent) {
  console.log('Parent exists:', parent.tagName);
} else {
  console.log('No parent element found');
}
Output
Parent exists: DIV
📊

Quick Reference

  • parentElement: Returns the parent element node or null.
  • parentNode: Returns the parent node, which can be an element or other node types.
  • Use parentElement when you want only element parents.
  • Always check for null to avoid errors.

Key Takeaways

Use parentElement to get the direct parent element of a DOM node.
Check if parentElement is not null before accessing it.
parentNode can return non-element nodes; prefer parentElement for elements.
The root element has no parent element, so parentElement returns null.
Changing parent element styles is easy once you select it via parentElement.