javascript - How to remove active class from all li elements except one that clicked? -
it doesn't let me complete slider in mind. , want note not use jquery. javascript. tried many ways, didn't take effect.
var ul = document.queryselector('ul'); var dots = []; (var = 0; < 5; i++) { var dot = document.createelement('li'); dots.push(dot); ul.appendchild(dot); } dots[2].setattribute('class', '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> here jsfiddle link: https://jsfiddle.net/heybetov1998/camuyve2/4/
you can hook event handler on dots. within event handler, this refer element on attached handler. can remove class others:
var ul = document.queryselector('ul'); var dots = []; (var = 0; < 5; i++) { var dot = document.createelement('li'); dot.addeventlistener("click", clickhandler); // ** hook handler dots.push(dot); ul.appendchild(dot); } dots[2].setattribute('class', 'active'); // here's handler function clickhandler() { var dots = document.queryselectorall("li"); (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 need support obsolete browsers don't have addeventlistener, this answer has function doing that.
that's minimal-changes version. there several changes i'd @ making:
don't use
setattributesetclassattribute. fails on old versions of ie, more importantly, replaces classes on element. @ classlist.the example above hooks event handler each dot, if have lot of dots, or add/remove them dynamically, might better off using event delegation hooking handler on container of dots , using
e.targetdetermine dot clicked.
Comments
Post a Comment