Reputation: 23
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
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
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
Reputation: 325
<!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
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
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