1

What would be the best way to add the active class to an "active/current" element with PLAIN JavaScript?

With jQuery you would use the typical:

$(selector).on('click', function(){
    $(selector).removeClass('active');
    $(this).addClass('active');
});

But with JavaScript (not vanilla JS, jQuery, etc)??

Heres my fiddle: http://jsfiddle.net/meEf4/2065/

vikash chander
  • 49
  • 1
  • 10
Angie R
  • 98
  • 1
  • 6

1 Answers1

2

You can first get the element that has active class. Since there will be only one <a> with active class so you can directly access the <a> Now replace that active class will no text. Finally, add the active class to the clicked <a> element.

First attach a click handler to all the <a> tags:

const navAnchor = document.querySelectorAll('a');

navAnchor.forEach(anchor => {
  anchor.addEventListener('click', addActive);
})

Now, create a function addActive as below:

function addActive(e) {
  const current = document.querySelector('.active');
  current.className = current.className.replace("active", "");
  e.target.className += "active";

}

jaber
  • 3
  • 4
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62