Reputation: 364
For example,
<div class="panel">
<div class="inner-panel">
<button onclick="hideParentElement()">
Hide
</button>
</div>
</div>
If I want to add a class to the outer most division, I need to fetch that element and add a class to it. How can this be achieved using pure javascript?
I have tried the following:
this.parentElement.parentElement.classList.add("classname");
This works but if there are more than 2 parentElements it is not the right way. Please suggest a better way
Upvotes: 7
Views: 9902
Reputation: 739
In case when your class list is changing dynamically:
let parent = this.parentElement;
while (!parent.classList.contains('panel'))
parent = parent.parentElement;
parent.classList.add('classname');
or much more simply
this.closest('div.panel').classList.add('classname');
Upvotes: 5
Reputation: 139
Kind of late to the party, but this seems to work:
var pn = element.parentNode
for(i=4;i>0;i--){
pn = pn.parentNode;
}
Upvotes: 0
Reputation: 2321
You have to cycle the parents like this.
var el = this.parentElement;
while(el.className != 'panel'){
el = el.parentElement;
}
//el is now your parent
el.className += "classname";
With pure Javascript this is the way to do it.
Upvotes: 3