简体   繁体   中英

JavaScript Add Class on Click of Element

I'm attempting to make a responsive navbar via a menu button and when said button is clicked a containing div appears with the navigation links. In order to do so when this element is clicked, I want the element to have the class 'toggled' added to it.

Here is my html:

        <div class="menu-container">
            <i class="fas fa-bars"></i>
        </div>

Here's the JavaScript:

$('fas.fa-bars').on('click', function() {
  $(this).addClass("toggled");
});

Could someone please help me out and let me know how to do this?!

You need to update the selector as .fas.fa-bars because .fas and .fa-bar are two different classes.

 $('.fas.fa-bars').on('click', function() { $(this).addClass("toggled"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="menu-container"> <i class="fas fa-bars">Click me</i> </div>

$('.fas.fa-bars').on('click', function() {
  $(this).addClass("toggled");
});

You should add dot . before class name in jQuery syntax. Without . it will be element selector, not class selector.

Check this w3schools article jQuery selectors

Your selector code is wrong, as @Sebastian Simon said. fas.fa-bars would match <fas class="fa-bars"> . You would need something like this: .fas.fa-bars . See the demo below.

 $('.fas.fa-bars').on('click', function () { $(this).addClass("toggled"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://kit.fontawesome.com/a076d05399.js" crossorigin="anonymous"></script> <div class="menu-container"> <i class="fas fa-bars"></i> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM