Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent element of nested child by class or name

I have html elements like follows with unknown hierarchy:

<div class="parent" name="parent">
  <div>
    <div>
      <div>
        <div onclick="get_parent(this)">
          Nested Child 1
        </div>
      </div>
    </div>
  </div>
</div>
<div class="parent" name="parent">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>

Is there any easy way to get parent of nested child by class or name?

Maybe there is some alternative to child.parentElement or child.parentNode I am not aware of which may help me?

Or looping through all parents until I get needed class or name is the only possible choice?

like image 790
Systems Rebooter Avatar asked Feb 16 '20 07:02

Systems Rebooter


People also ask

How do you find the parent element of a parent element?

Use the closest() method to get the closest parent element by tag, e.g. child. parentElement. closest('div') . The closest() method traverses the Element and its parents until it finds a node that matches the provided selector.

What is the use of parent () and child () method in jQuery?

parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.


1 Answers

I think closest is the best solution.

function get_parent(elem) {
/*** For Class ***/
 // var x = elem.closest(".parent").className;
 /*** For Name ***/
   var x = elem.closest(".parent").attributes["name"].value;
  document.getElementById("demo").innerHTML = x;
}
<div class="parent" name="parent1">
<div>
  <div>
    <div>
      <div onclick="get_parent(this)">
        Nested Child 1
      </div>
    </div>
  </div>
</div>
</div>
<div class="parent" name="parent2">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>

<p id="demo"></p>
like image 135
Mark Valenzuela Avatar answered Sep 28 '22 07:09

Mark Valenzuela