1

I try to change a css class on click. But it does not work. What am I doing wrong?

<div id="tags">
    <span class="badge badge-secondary">Watchlist</span>
    <span class="badge badge-secondary">Watched</span>
    <span class="badge badge-secondary">Like</span>
</div>

Script:

<script>
    $( "#tags" ).click(function() {
        .find("span")
        .removeClass("badge-secondary")
        .addClass("badge-primary");
    });
</script>

I am thankful for every hint.

3
  • Did you include jQuery? Commented Sep 3, 2020 at 18:02
  • yes. i did. other things are working. :) Commented Sep 3, 2020 at 18:05
  • 1
    Should be a big error right there in your console.... use your developer tools. Commented Sep 3, 2020 at 18:09

1 Answer 1

3

You can use .toggleClass() directly on spans:

$( "#tags span" ).on('click', function(e) {
    $(this).toggleClass('badge-secondary badge-primary')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<div id="tags">
    <span class="badge badge-secondary">Watchlist</span>
    <span class="badge badge-secondary">Watched</span>
    <span class="badge badge-secondary">Like</span>
</div>

Sign up to request clarification or add additional context in comments.

4 Comments

this is working. thank you. BUT: i want to use the css of bootstrap. any idea on how to do that? the secondary bootstrap badge should change to the primary bootstarp badge.
last question: this code just works in any browser. but it is not working on my local mamp?
try to look in the console and mamp console.
Closing bracket missing. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.