Showkat Ali
Showkat Ali

Reputation: 23

How to find a parent with a known class in plain JavaScript

Please look at this html code first:

<div class="parent">
  <div class="child">
    
  </div>
  <div class="child">
    <!-- Some code here -->
  </div>
</div>
<div class="parent>
  <!-- some code here -->
</div>

Suppose, I'm in "child" class, & I need to get the closest parent class of a "child". Remember, there are more than one "parent" class, I just need the closest "parent" only using plain JavaScript, without using JQuery.

How to do that?

Upvotes: 2

Views: 2397

Answers (5)

Icado
Icado

Reputation: 69

Use this.

var parent = document.querySelectorAll(".child");
for(var p = 0; p < parent.length; p++) {
    parent[p].parentElement.classList.add("newClass");
    //parent[p].//do something
}

or directly quote the parent

var parent = document.querySelectorAll(".child");
for(var p = 0; p < parent.length; p++) {
    parent[p].closest(".parent").classList.add("newClass");
    //parent[p].closest(".parent").//do something
}

Upvotes: 0

Varun Goel
Varun Goel

Reputation: 475

You can create a helper function and resuse it.Hope this is what you are looking for -

let getParentClass = node => {
  return node.parentNode.classList.value;
}

let child = document.querySelectorAll('.child')[0]; // find the node
console.log(getParentClass(child));
<div class="parent">
  <div class="child">

  </div>
  <div class="child">
    <!-- Some code here -->
  </div>
</div>
<div class="parent">
  <!-- some code here -->
</div>

Upvotes: 2

<!DOCTYPE html>
<div class="parent">
  <div class="child">

  </div>
  <div class="child">
    <!-- Some code here -->
  </div>
</div>
<div class="parent">
  <!-- some code here -->
</div>
<script>
const child = document.getElementsByClassName('child')[0];
console.log(child)
const parent = child.closest('.parent');
console.log(parent)
</script>

Upvotes: 0

Sifat Haque
Sifat Haque

Reputation: 6067

You can use parentNode to get the closest parent. Or you can use closest from vanilla js.

const child = document.querySelector('.child');
const closestParent = child.parentNode;

const child = document.querySelector('.child');
const closestParent = child.parentNode;
console.log(closestParent);

// Or you can use closest
const closest = child.closest('.parent');

console.log(closest);
<div class="parent">
  <div class="child">
    
  </div>
  <div class="child">
    <!-- Some code here -->
  </div>
</div>

Upvotes: 0

Mamun
Mamun

Reputation: 68933

You can try using closest()

document.querySelectorAll('.child').forEach(function(child){
  console.log(child.closest('.parent'));
});
<div class="parent">
  <div class="child">
    
  </div>
  <div class="child">
    <!-- Some code here -->
  </div>
</div>
<div class="parent">
  <!-- some code here -->
</div>

Upvotes: 6

Related Questions