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');
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With