How Can We Help?
-
HTML
-
CSS
- Introduction to CSS
- Before learning CSS?
- SELECTOR
- Example
- Box Model
- Comments
- Colors
- Background Color
- Text Color
- Border Color
- Backgrounds
- Borders
- Margins
- Padding
- Height, Width, and Max-width
- Outline
- Text
- Font Style, Font Size & Shorthand
- Links
- Display and Position
- Lists
- Tables
- Pseudo-classes and Combinators
- Flexbox
- Grid
- Flexbox vs Grid
- Responsive Web Design
- Media Queries
- Responsive Images
- Fluid Layouts
- Transforms, Transitions, and Animations
-
JavaScript
- Introduction to JavaScript
- Hello World
- Syntax
- Variables
- Data Types
- Numbers
- Boolean type
- String
- Objects
- Primitive vs Reference Values
- Arrays
- Arithmetic Operators
- Remainder Operator
- Assignment Operators
- Comparison Operators
- Logical Operators
- if statement
- if else
- if else if
- Ternary Operator
- Object Spread
- Switch case
- While Loop
- do…while Loop
- Loop
- break
- continue
- Functions
- Storing functions in variables
- Anonymous Functions
- Pass-By-Value
- Recursive Function
- Object Methods
- Constructor Function
- this Keyword
- Object Properties
- for…in Loop
- Object.values
- Object.assign
- Class
- Getters and Setters
- Function Type
- Closures
- Arrow Functions
- When You Should Not Use Arrow Functions
- Rest Parameters
- Callbacks
- Promises
- async/await
-
JavaScript DOM
- JavaScript DOM
- getElementById
- getElementsByName
- getElementsByTagName
- getElementsByClassName
- querySelector
- JavaScript Get the Parent Element parentNode
- Getting Child Elements
- JavaScript Siblings
- CreateElement
- appendChild
- JavaScript textContent
- JavaScript innerHTML
- JavaScript innerHTML vs createElement
- Working with Attributes
- JavaScript Style
- Working with Events
-
React
< 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 thequerySelector()
method. - Second, find the parent node of the element.
Summary
- The
node.parentNode
returns the read-only parent node of a specified node ornull
if it does not exist. - The
document
andDocumentFragment
do not have a parent node.
Table of Contents