javascript - Add active class to current element with JS (not Jquery) -
this question has answer here:
what best way add active class "active/current" element plain javascript?
with jquery use typical:
$(selector).on('click', function(){ $(selector).removeclass('active'); $(this).addclass('active'); });
but javascript (not vanilla js, jquery, etc)??
heres fiddle: http://jsfiddle.net/meef4/2065/
you can first element has active
class. since there 1 <a>
active
class can directly access <a>
element using [0]
. replace active
class no text. finally, add active
class clicked <a>
element.
first attach click handler <a>
tags:
var elements = document.getelementsbytagname("a"); (var = 0; < elements.length; i++) { elements[i].addeventlistener("click", clickhandle); }
now, create function clickhandle
below:
function clickhandle(event) { var anchor = document.getelementsbyclassname("active"); anchor[0].classname = anchor[0].classname.replace(/active/g, ""); event.target.classname += "active"; }
Comments
Post a Comment