How Can We Help?
< All Topics

JavaScript Get the Parent Element parentNode

Introduction to parentNode attribute

To get the parent node of a specified node in the DOM tree, you use the parentNode property:

let parent = node.parentNode; 

The parentNode is read-only.

The Document and DocumentFragment nodes do not have a parent. Therefore, the parentNode will always be null.

If you create a new node but haven’t attached it to the DOM tree, the parentNode of that node will also be null.

JavaScript parentNode example

See the following HTML document:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript parentNode</title>
</head>
<body>
    <div id="main">
        <p class="note">This is a note!</p>
    </div>

    <script>
        let note = document.querySelector('.note');
        console.log(note.parentNode);
    </script>
</body>
</html>

The following picture shows the output in the Console:

How it works:

  • First, select the element with the .note class by using the querySelector() method.
  • Second, find the parent node of the element.

Summary

  • The node.parentNode returns the read-only parent node of a specified node or null if it does not exist.
  • The document and DocumentFragment do not have a parent node.

Table of Contents