window.onload = function() {
var elements = document.querySelectorAll('body *');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener("click", function(e) {
console.log(e.target.className + "->" + e.target.parentNode.className);
});
}
};
.outer_box_green{
border-style:solid;
border-color:green;
}
.inner_box_thick{
margin:2px;
padding:3px;
border-style:dashed;
border-width:4px;
}
.line_1{
font-size:2em;
display:block;
}
.line_2{
font-size:4em;
}
<body>
<div class="outer_box_green">
<div class="inner_box_thick another_inner_box_class">
<span class="line_1">Line 1</span>
<span class="line_2">Line 2</span>
<div>Line 3</div>
</div>
</div>
</body>
Using vanilla Javascript, how can we get the classes of a clicked element and all the classes of the "ancestor" elements the clicked element is nested within. For example, if we have
<div class="outer_box_green">
<div class="inner_box_thick another_inner_box_class">
<span class="line_1">Line 1</span>
<span class="line_2">Line 2</span>
<div>Line 3</div>
</div>
</div>
The desired behavior is to get Javascript arrays containing ancestors' classes when an element is clicked:
["line_1", "inner_box_thick", "another_inner_box_class", "outer_box_green"]
["line_2", "inner_box_thick", "another_inner_box_class", "outer_box_green"]
["inner_box_thick", "another_inner_box_class", "outer_box_green"]
I figured out how to print the classes using parentNode.className
but it only goes up one level (see snippet). How can this be done to get all CSS classes of all nested HTML ancestors at once?
You can move up the DOM tree until the parentNode
becomes null
.
window.onload = function() {
var elements = document.querySelectorAll('body *');
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener("click", function(e) {
const classNames = [];
let node = e.target;
while(node != null){
if(node.className) classNames.push(node.className);
node = node.parentNode;
}
console.log(...classNames);
});
}
};
.outer_box_green {
border-style: solid;
border-color: green;
}
.inner_box_thick {
margin: 2px;
padding: 3px;
border-style: dashed;
border-width: 4px;
}
.line_1 {
font-size: 2em;
display: block;
}
.line_2 {
font-size: 4em;
}
<div class="outer_box_green">
<div class="inner_box_thick another_inner_box_class">
<span class="line_1">Line 1</span>
<span class="line_2">Line 2</span>
<div>Line 3</div>
</div>
</div>