<ul class="list">
<li id="item1"> text 1 </>
<li id="item2"> text 2 </>
<li id="item3"> text 3 </>
</ul>
<div class="links">
<a href="#item1" data-active='#item1'> add class to text 1 </a><br>
<a href="#item2" data-active='#item2'> add class to text 2 </a><br>
<a href="#item3" data-active='#item3'> add class to text 3 </a>
</div>
li.active {
color: red;
}
document.querySelector('.links').addEventListener(
'click',
(e) => {
const id = e.target.dataset.active;
console.log(id);
if (id === undefined) {
return;
}
document.querySelector('.active')?.classList.remove('active');
document.querySelector(id).classList.add('active');
}
)
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.