Mariton
Mariton

Reputation: 621

Is there a way to return the top or second parent element of a specified element using JavaScript?

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

Answers (3)

Scott Marcus
Scott Marcus

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

Nick Timmer
Nick Timmer

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

Zakaria Acharki
Zakaria Acharki

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

Related Questions