Home > Blockchain >  How to Change a Font Class Name Inside a Link With JQuery
How to Change a Font Class Name Inside a Link With JQuery

Time:10-22

I'm trying to change the font class name after clicking the link with Javascript and jQuery.

The button example:

<a class='pe-1' onclick='change(this, 24)'><i class='bx bx-bookmark'></i></a>

If I try this way below will change the class from the link instead of the class from the font...

Function example 1:

function change(button, id) {

var changeButton = $(button);

changeButton.removeClass("bx-bookmark").addClass("bxs-bookmark");

}

Unfortunately doing the basic way (like my example below) doesn't really work for me since is going to change the value from all posts instead of just that one post.

Function example 2:

function change(button, id) {

var changeButton = $(button);

$(".bx").removeClass("bx-bookmark").addClass("bxs-bookmark");

}

What I'm missing?

CodePudding user response:

You would generally use $(this).find('bx').removeClass("bx-bookmark").addClass("bxs-bookmark"); to find the child within the link clicked

Here's a way you could do it without the onclick attribute in the html
and I even made it a toggle :-)

<a class='pe-1'><i class='bx bx-bookmark'></i></a>
$(document).ready(function() {

    // on any .pe-1 click
    $('.pe-1').click(function(){

        // find the child with the class .bx
        target = $(this).find('.bx');

        // if it has class bx-bookmark
        if (target.hasClass('bx-bookmark')){
            // remove it and add bxs-bookmark
            target
                .removeClass("bx-bookmark")
                .addClass("bxs-bookmark");
        }else{
            // we assume it has bxs-bookmark already
            //  so swap it back
            target
                .removeClass("bxs-bookmark")
                .addClass("bx-bookmark");
        };
    });

});

I wasn't sure what id was for so I removed it. If that's important just let me know what it's for and I'll figure out a solution.
Hope this helps!

  • Related