I am trying to remove an active
class from all elements. I already created the loop event. Inside the function the click event occurs where I wanted to remove a class from all a
of that loop. But, it seems that I can't write this block of code correctly:
const links = document.querySelectorAll('.link-block a');
links.forEach(el => {
el.addEventListener('click', e => {
el.classList.remove('active');
})
})
Full Code:
const texts = document.querySelectorAll('.content p > span'); const links = document.querySelectorAll('.link-block a'); links.forEach(el => { el.addEventListener('click', e => { texts.forEach(text => text.classList.add('hidden')); const id = e.target.getAttribute('href'); el.classList.remove('active'); e.target.classList.add('active'); document.querySelector(id).classList.remove('hidden'); }); });
.hidden { display: none; }.active { color: #f0f; }
<section> <section class="content"> <p> <span id="content-1">Sample Text for Content 1.</span> <span id="content-2" class="hidden">Sample Text for Content 2.</span> <span id="content-3" class="hidden">Sample Text for Content 3.</span> </p> </section> <section class="link-block"> <a href="#content-1" class="active">Content 1</a> <a href="#content-2">Content 2</a> <a href="#content-3">Content 3</a> </section> </section>
You would need another loop to remove a class from each element.
el.classList.remove('active');
in your code was referring to the current element, not to the collection of elements.
const texts = document.querySelectorAll('.content p > span'); const links = document.querySelectorAll('.link-block a'); links.forEach(el => { el.addEventListener('click', e => { texts.forEach(text => text.classList.add('hidden')); const id = e.target.getAttribute('href'); links.forEach(el => { el.classList.remove('active'); }); e.target.classList.add('active'); document.querySelector(id).classList.remove('hidden'); }); });
.hidden { display: none; }.active { color: #f0f; }
<section> <section class="content"> <p> <span id="content-1">Sample Text for Content 1.</span> <span id="content-2" class="hidden">Sample Text for Content 2.</span> <span id="content-3" class="hidden">Sample Text for Content 3.</span> </p> </section> <section class="link-block"> <a href="#content-1" class="active">Content 1</a> <a href="#content-2">Content 2</a> <a href="#content-3">Content 3</a> </section> </section>
links.forEach(el => {
el.addEventListener('click', e => {
links.forEach(element => {
element.classList.remove('active');
});
texts.forEach(text => text.classList.add('hidden'));
const id = e.target.getAttribute('href');
e.target.classList.add('active');
document.querySelector(id).classList.remove('hidden');
});
});
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.