I have below HTML:
<div id="parent">
<div>
<div>
//needs to get the inner HTML of this.
</div>
<p>
</p>
</div>
<div>
<div>
//needs to get the inner HTML of this.
</div>
<p>
</p>
</div>
<div>
<div>
//needs to get the inner HTML of this.
</div>
<p>
</p>
</div>
...10 more
</div>
Could someone please confirm if is it possible to have one click event listener to capture the inner HTML of grandchild of the parent node on mouse click?
I have tried using below
document.getElementById('parent').addEventListener('click', event => {
// what to do here to get the inner HTML of granchild div
})
The problem with above approach is if I click on grand child p tag then it gives the inner html of p tag but I always want the inner html of the first div.
Please use this code.
document.getElementById("parent").addEventListener("click", function() {
console.log(this.children[0].innerHTML);
});
You can use event.target.closest("div") and check if has firstElementChild it means you click on p tag and firstElementChild gives you the correct div and if it is null it means you already click on corrcet div.
Here is working sample:
document.getElementById('parent').addEventListener('click', event => {
var firstDiv = event.target.closest("div").firstElementChild;
if(!firstDiv)
firstDiv = event.target;
console.log(firstDiv.innerHTML);
})
<div id="parent">
<div>
<div>
1. needs to get the inner HTML of this.
</div>
<p>
1.P
</p>
</div>
<div>
<div>
2.needs to get the inner HTML of this.
</div>
<p>
2.P
</p>
</div>
<div>
<div>
3.needs to get the inner HTML of this.
</div>
<p>
3.P
</p>
</div>
</div>
If you want to attach event listener to each of the grandchild div, then
document.getElementById('.grandchild-div-id').forEach(item => {
item.addEventListener('click', event => {
//handle click
})
})