Toggle class onclick in plain inline JavaScript

in Code Write a comment

Learn how to select an HTML element by class and toggle its class in JavaScript.

Suppose there’s a button that needs to show/hide a newsletter banner. Newsletter visibility is controlled by the CSS classes, adding Bootstrap 4 class d-none will hide a newsletter.

You can use jQuery and do that:

$(document).ready(function() {
  $('.toggle-newsletter').click(function() {
    $('.newsletter').toggleClass('d-none');
  });
});

But if you’re not using a jQuery framework (in most of the cases you shouldn’t) you can use plain JavaScript.


Hi, I'm Renat 👋

 


Let’s change our example above to plain JS.

<a href="#" class="toggle-newsletter" onclick="event.preventDefault(); document.getElementsByClassName('newsletter')[0].classList.toggle('d-none');">Show/hide newsletter</a>

The inline JS will do exactly the same thing – it will toggle our newsletter box.

If you find this post useful or know other ways please let me know in the comments below. 
Cheers,
Renat Galyamov

Want to share this with your friends?
👉renatello.com/javascript-toggle-class-onclick

PS: Make sure you check other JavaScript tutorials, e.g. how to create an array of numbers in JavaScript, generate an array of years in JavaScript or remove item from an array of objects by object property in JavaScript.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment