I have a class. How do I know this class parents id.
Asked
Active
Viewed 133 times
0
-
2Does this answer your question? [Get parent class name from child with ES6?](https://stackoverflow.com/questions/31644662/get-parent-class-name-from-child-with-es6) – asky Feb 09 '20 at 02:33
1 Answers
3
Elements in HTMl can have only one parent node. I am not sure if you want retrieve id of grandParent class in the example or not. If you want to retrieve ids of all the ancestor nodes, please update the question.
const child = document.querySelector('.child') // Selecting the class you want to work with.
console.log(child);
const parent = child.parentElement.getAttribute('id') // Getting id of parent node.
console.log('parent id: ', parent);
<div id='1' class='grandParent'>
<div id='2' class='parent'>
<div id='3' class='child'>
Hi
</div>
</div>
</div>

Tps
- 194
- 5