简体   繁体   中英

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?

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>

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>

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>

<!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>

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM