4

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');
SukieA
  • 51
  • 1
  • 4
  • 2
    You've searched and searched? what about this question, which is a duplicate of another question, with 21 answers? http://stackoverflow.com/questions/2155737/remove-css-class-from-element-with-javascript-no-jquery – Djave Dec 10 '15 at 15:15
  • And what's your relevant, "[MCVE]" HTML? – David Thomas Dec 10 '15 at 15:19
  • What are you having problems with, attaching an event handler, getting an element by selector or adding and removing a css class? – bug-a-lot Dec 10 '15 at 15:21
  • For more examples of jQuery functionality and its vanilla DOM equivalent, see http://youmightnotneedjquery.com/ – Joe Attardi Dec 10 '15 at 15:45

2 Answers2

5

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>
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
0

All modern browsers have support for document.querySelector/document.querySelectorAll, which are essentially the same thing as the jQuery $ function.

(For supported browser info check out http://caniuse.com/#feat=queryselector.

Instead of calling addClass/removeClass on a jQuery object, the DOM API exposes a property of elements called className. This is same as the class attribute on an element:

this.className = 'current';

Lastly, event handlers are registered with the addEventListener function. The arguments are the event name and the event handler function.

Joe Attardi
  • 4,381
  • 3
  • 39
  • 41