Reputation: 621
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
.
Upvotes: 5
Views: 5919
Reputation: 65825
"I will probably have it execute when a user clicks a radio button or on some type of click."
Then just set up the click event on the section elements:
var sections = Array.prototype.slice.call(document.querySelectorAll("section"));
sections.forEach(function(section){
section.addEventListener("click", function(){
console.log(this.id);
});
});
<section id="one">
<div>
<ul>
<li id="myLI">Coffee</li>
<li>Tea</li>
</ul>
</div>
</section>
<section id="two">
<div>
<ul>
<li id="myLI">Coffee</li>
<li>Tea</li>
</ul>
</div>
</section>
<section id="three">
<div>
<ul>
<li id="myLI">Coffee</li>
<li>Tea</li>
</ul>
</div>
</section>
Upvotes: 2
Reputation: 425
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?
Upvotes: 2
Reputation: 67525
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>
Upvotes: 7