Is there an easy way to remove all other classes except the eventarget in with JavaScript.
For example, if I have a UL:
<ul>
<li>list element</li>
<li>list element</li>
<li>list element</li>
<li>list element</li>
<li>list element</li>
<li>list element</li>
</ul>
And I add click event listener with an event handler:
var UL = document.querySelector('ul');
function eventHandler(e) {
var thiz = e.target;
document.querySelectorAll('ul li').classList.remove("active");
thiz.classList.add("active");
}
UL.addEventListener('click', function (e) {
eventHandler(e);
});
How can I add a class on the element being clicked, while removing all the other "active" classes.
Here's a fiddle http://jsfiddle.net/298ZV/
this
refers to the element that triggered the event... so why not set the class directly tothis
?eventHandler
directly into the listener, like so:UL.addEventListener('click', eventHandler)
since they take the same arguments