I would like to get the top parent element (section) of a myLI
id.
My HTML code is:
<section>
<div>
<ul>
<li id="myLI">Coffee</li>
<li>Tea</li>
</ul>
</div>
</section>
My code is:
var x = document.getElementById("myLI").parentElement.nodeName;
My code returns UL
but I would like for it to return section
.
To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.
By using querySelector() and closest() methods is possible to get the parent element. querySelector() returns the first element that matches a specified CSS selector(s) in the document. closest() searches up the DOM tree for the closest element which matches a specified CSS selector.
Use . children property to get access of all the children of the element. Select the particular child based on the index.
The read-only parentNode property of the Node interface returns the parent of the specified node in the DOM tree. Document and DocumentFragment nodes can never have a parent, so parentNode will always return null . It also returns null if the node has just been created and is not yet attached to the tree.
If you want to target the parent by tagName you could use .closest(selector);
like :
var x = document.getElementById("myLI").closest('section');
NOTE : Take a look to the Browser compatibility section.
Hope this helps.
var x = document.getElementById("myLI").closest('section');
console.log(x.tagName);
<section>
<div>
<ul>
<li id="myLI">Coffee</li>
<li>Tea</li>
</ul>
</div>
</section>
var topParent = document.getElementById("myLI");
while( topParent.parentElement.nodeName != 'BODY' ){
topParent = topParent.parentElement;
}
console.log( topParent.nodeName );
<section>
<div>
<ul>
<li id="myLI">Coffee</li>
<li>Tea</li>
</ul>
</div>
</section>
So I'm assuming you want the element right before the 'BODY' element?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With