Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla Javascript - Adding class to element 1 and remove class from element 2 on click of element 1

Tags:

javascript

I've been told I can no longer use jQuery on a project I'm building, so I'm forced to use vanilla Javascript which can sometimes be way over my head. I'm hoping to simply convert this jQuery to js. I've searched and searched on Stack Overflow to no avail, but I feel like it shouldn't be that difficult. Any help would be amazing!

$('.navbuttoncontainer a').on( 'click', function() {
$('.navbuttoncontainer .current').removeClass('current');
$(this).addClass('current');
like image 996
SukieA Avatar asked Sep 16 '25 17:09

SukieA


1 Answers

You could attach a click event listener to the .navbuttoncontainer element.

Then determine whether the a element was clicked by checking the tag name of the target element (e.target). Use the .add()/.remove() methods on the classList property of the element in order to add/remove the class.

document.querySelector('.navbuttoncontainer').addEventListener('click', function (e) {
  var target = e.target;
  
  if (target.tagName === 'A') {
    e.currentTarget.querySelector('.current').classList.remove('current');
    target.classList.add('current');
  }
});
.current {
  color: #f00;
}
<div class="navbuttoncontainer">
  <a class="current">Initially current item</a>
  <a>Second item</a>
  <a>Third item</a>
</div>
like image 147
Josh Crozier Avatar answered Sep 18 '25 08:09

Josh Crozier