Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 757
Mariton Avatar asked Oct 31 '17 21:10

Mariton


People also ask

How do you find the parent of an element?

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.

How do you get the parent element in querySelector?

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.

Which Javascript function is used to select the child tag from the parent element?

Use . children property to get access of all the children of the element. Select the particular child based on the index.

What is parentNode in Javascript?

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.


2 Answers

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>
like image 139
Zakaria Acharki Avatar answered Sep 16 '22 19:09

Zakaria Acharki


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?

like image 45
Nick Timmer Avatar answered Sep 19 '22 19:09

Nick Timmer