Why parentElement ?
The HTML DOM parentElement () method returns a parent of the specified element. Returns null if the parent is not a node or no parent. This property is read-only.
Syntax:
node.parentElement
DOM parentNode VS parentElement :
parentElement is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.
In most cases, it is the same as parentNode. The only difference comes when a node’s parentNode is not an element. If so, parentElement is null.
As an example:
document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element
document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null
(document.documentElement.parentNode === document); // true
(document.documentElement.parentElement === document); // false
parentElement Examples
Example 1
<body>
<p>
The parentElement method in the pElementFunction()
function will work when the button is pressed. As a
result, the color and size of the div boxes will change.
</p>
<div class="box">
<button onclick="pElementFunction()" class="but">CLICK</button>
</div>
<script>
function pElementFunction() {
let box = document.querySelector(".but").parentElement;
box.style.background = "orange";
box.style.width = "250px";
box.style.height = "250px";
}
</script>
</body>
Example 2
<body>
<p>
The parentElement method in the pElementFunction()
function will work when the button is pressed. As a
result, the color and size of the div boxes will change.
</p>
<div class="box">
<button onclick="pElementFunction()" class="but">CLICK</button>
</div>
<p id="result"></p>
<script>
function pElementFunction() {
let box = document.querySelector(".but").parentElement;
document.getElementById("result").innerHTML = box.nodeName;
}
</script>
</body>
Example 3
<p>
The parentElement method in the pElementFunction()
function will work when the button is pressed. As a
result, the color and size of the div boxes will change.
</p>
<div class="box">
<button onclick="pElementFunction()" class="but">CLICK</button>
</div>
<script>
function pElementFunction() {
let box = document.querySelector(".but").parentElement;
box.style.transform = "translate(-300px,-300px)"
}
</script>
Leave a comment