Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

228
Views
How to get the first div element on event listener

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Please use this code.

document.getElementById("parent").addEventListener("click", function() {
    console.log(this.children[0].innerHTML);
});
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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
  })
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!