I am trying to select six elements with the class name .hours but using document.querySelectorAll() isn't working and if I use document.querySelector() it returns only the first class with the name .hours, using document.getElementsByClassName() isn't working either. Please help :)
const hoursTime = document.getElementsByClassName('hours');
const lastTime = document.querySelectorAll('.last-time');
hoursTime.onclick = function() {
hoursTime.innerHTML = "Clicked";
}
<div >
<div >
<div >
<div >
<h3>Work</h3>
<img src="/images/icon-ellipsis.svg" alt="">
</div>
<div >
<h1 >0hrs</h1>
<p >Select TIme Tracking</p>
</div>
</div>
</div>
<div >
<div >
<div >
<h3>Play</h3>
<img src="/images/icon-ellipsis.svg" alt="">
</div>
<div >
<h1 >0hrs</h1>
<p >Select TIme Tracking</p>
</div>
</div>
</div>
<div >
<div >
<div >
<h3>Study</h3>
<img src="/images/icon-ellipsis.svg" alt="">
</div>
<div >
<h1 >0hrs</h1>
<p >Select TIme Tracking</p>
</div>
</div>
</div>
<div >
<div >
<div >
<h3>Exercise</h3>
<img src="/images/icon-ellipsis.svg" alt="">
</div>
<div >
<h1 >0hrs</h1>
<p >Select TIme Tracking</p>
</div>
</div>
</div>
<div >
<div >
<div >
<h3>Social</h3>
<img src="/images/icon-ellipsis.svg" alt="">
</div>
<div >
<h1 >0hrs</h1>
<p >Select TIme Tracking</p>
</div>
</div>
</div>
<div >
<div >
<div >
<h3>Self Care</h3>
<img src="/images/icon-ellipsis.svg" alt="">
</div>
<div >
<h1 >0hrs</h1>
<p >Select TIme Tracking</p>
</div>
</div>
</div>
</div>
Why is it not working?
CodePudding user response:
You have to use forEach
function fn() {
this.innerHTML = 'clicked'
}
document.querySelectorAll('.hours').forEach(e => e.addEventListener('click', fn))