You can hook up an event handler on the dots. Within the event handler, this
will refer to the element on which you attached the handler. Then you can remove the class from all the others:
var ul = document.querySelector('ul');
var dots = [];
for (var i = 0; i < 5; i++) {
var dot = document.createElement('li');
dot.addEventListener("click", clickHandler); // ** Hook up the handler
dots.push(dot);
ul.appendChild(dot);
}
dots[2].setAttribute('class', 'active');
// Here's the handler
function clickHandler() {
var dots = document.querySelectorAll("li");
for (var n = 0; n < dots.length; ++n) {
if (dots[n] !== this) {
dots[n].className = "";
}
}
this.className = "active";
}
li {
width: 20px;
height: 20px;
background-color: lightgrey;
text-decoration: none;
display: inline-block;
border-radius: 100%;
margin-right: 15px;
}
.active {
background-color: grey;
}
<ul></ul>
If you need to support obsolete browsers that don't have addEventListener
, this answer has a function for doing that.
That's the minimal-changes version. But there are several changes I'd look at making:
Don't use setAttribute
to set the class
attribute. It fails on very old versions of IE, but more importantly, it completely replaces the classes on the element. Look at classList.
The example above hooks up an event handler to each dot, but if you have a lot of dots, or you add/remove them dynamically, you might be better off using event delegation by hooking up the handler on the container of the dots and then using e.target
to determine which dot was clicked.