9

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?

2
  • 1
    That is one way. The other way is to have the information you need from the parent available to the child through attributes.
    – Ibu
    Commented Feb 16, 2020 at 7:15
  • Like this one? stackoverflow.com/a/12981248/863110 (or jQuery .parents)
    – Mosh Feu
    Commented Feb 16, 2020 at 7:16

5 Answers 5

11

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>

4

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>

3

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>

0

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>

0

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
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.