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

107
Views
How to add click to items with same classes in pure javascript?

I don't know how I can catch individual elements with the same classes in pure javascript (without jQuery).

example:

<div class="item">
    <div class="divInside"></div>
</div>
<div class="item">
    <div class="divInside"></div>
</div>
<div class="item">
    <div class="divInside"></div>
</div>

Specifically, I want to catch a "divInside" for the "item" so that I can add a click function. Can someone help me?

Thank you in advance for your answer.

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

0

document.querySelectorAll('.divInside') will get you a list of all the elements in the document with the divInside class.

Adding a click event to all of them should be as easy as this:

const elems = document.querySelectorAll('.divInside')

elems.forEach(element => element.addEventListener('click', e => {
//Whatever you want to do
}))

What querySelectorAll does is it essentially lets you search for elements on the DOM using a matching CSS selector. If you want to get just the first element that matches a selector, you can use document.querySelector instead.

about 4 years ago · Juan Pablo Isaza Report

0

You would use querySelectorAll followed by forEach to loop through and add the click events.

function clickEvent(e){
   console.log(e);
}

document.addEventListener('DOMContentLoaded', function(){
    document.querySelectorAll('.item > .divInside').forEach((div)=>{
        div.addEventListener('click', clickEvent);
    });
});
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!