var expandIt=document.getElementsByClassName('k-grid');
function expandClickcurrentNOTs () {
console.log('pressed'); // works
console.log(e.target); // but need to add class to only class elem clicked
}
for (i = 0; i < expandIt.length; i++) {
expandIt[i].addEventListener("click", expandClickcurrentNOTs);
}
Above is what I have; I simply want to add a style when one of my class elements is clicked.. But only to that specific one, not all other class elements.
Get the elements using Document.querySelectorAll()
, which returns a static NodeList the you can iterate with NodeList.forEach()
. Add an event handler to each element, and in the handler use toggle to add/remove the class name from the element's classList .
const expandIt = document.querySelectorAll('.k-grid') .forEach(el => el.addEventListener('click', () => { el.classList.toggle('pressed') }))
.k-grid.pressed { color: red; }
<div class="k-grid">k-grid</div> <div class="k-grid">k-grid</div> <div class="k-grid">k-grid</div> <div class="k-grid">k-grid</div> <div class="k-grid">k-grid</div> <div class="k-grid">k-grid</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.