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.
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.
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);
});
});