Systems Rebooter
Systems Rebooter

Reputation: 1409

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?

Upvotes: 8

Views: 19292

Answers (5)

ritchie
ritchie

Reputation: 455

Similar to Raj. Prevent getting null at the end with this.

Find the parent with class 'highlight'. Stop searching at the body tag. In other words you can't search further than the body tag.

Example Use:

if (getParent(el,'highlight')[1]){ 
    let e = getParent(el,'highlight')[0]
    console.log('element found is',e)
 }
function getParent(el,cl){
        let e = el
        let tag = ''
        while( tag !== 'HTML' && ! hasClass(e,cl) ){
            e=e.parentElement;
            tag = e.tagName
        }
        let found = (tag === 'HTML') ? [null,false] : [e,true]
        console.log('result is ',found);
        return found
}

Here is a function I use often.

function hasClass(el,cl){
                if (el == null){return false}
                return (el.classList.contains(cl)) ? true : false
    }

Upvotes: 0

Raj Yadav
Raj Yadav

Reputation: 10808

The pure JS only solution you can try!

function getParent(ele, parentClass="parent"){
   var e = ele;
   while(!e.classList.contains(parentClass)){
      e=e.parentElement;
   }
   console.log(e);
   return e;
}
<div class="parent">
   <div>
      <div>
         <div>
            <div onclick="getParent(this)">CHILD 1</div>
         </div>
      </div>
   </div>
</div>


<div class="second_parent">
    <div>
        <div onclick="getParent(this,'second_parent')">CHILD 2</div>
    </div>
</div>

Upvotes: 4

Mark Valenzuela
Mark Valenzuela

Reputation: 358

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>

Upvotes: 11

artanik
artanik

Reputation: 2714

You can use node.closest() with polyfill if you need.

function get_parent (node, selector) {
  console.log(node.closest(selector));
}
<div class="parent" name="parent">
  <div>
    <div>
      <div>
        <div onclick="get_parent(this, '.parent')">
          Nested Child 1
        </div>
      </div>
    </div>
  </div>
</div>

<div class="other-parent" name="other-parent">
  <div>
    <div onclick="get_parent(this, '.other-parent')">
      Nested Child 2
    </div>
  </div>
</div>

Upvotes: 3

Yasaman.Mansouri
Yasaman.Mansouri

Reputation: 560

you should loop "parent()" function jquery.

function get_parent(a){
  $(a).parent().parent();
  console.log("test",$(a).parent().parent());
}
<div class="parent" name="parent">
  <div>
    <div onclick="get_parent(this)">
      Nested Child 2
    </div>
  </div>
</div>
<script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>

Upvotes: 0

Related Questions