user3544484
user3544484

Reputation: 851

Change link with jQuery depending on class

Is there a way to change the link text on the fly with jQuery, if the link class changes?

Initial state (no class):

<a href="#" class="">Save This</a>

If above is clicked it is given a class as below:

<a href="#" class="saved">Save This</a>

I would like to end up with this:

<a href="#" class="saved">Remove This</a>

What I would like if is the class changes to "saved", I want to change the initial text 'Save This' to 'Remove This'.

Upvotes: 1

Views: 97

Answers (4)

Kunj
Kunj

Reputation: 2018

Try this:

$('a').click(function(e) {
        e.preventDefault();
        $(this).hasClass('saved')?$(this).html('Remove This'):$(this).addClass('saved');
    });

Upvotes: 0

Suganth G
Suganth G

Reputation: 5156

Try this:

DEMO

Assigning id will provide unique operation

HTML:

<a id="btn" href="#" class="">Save This</a>

SCRIPT:

 $("#btn").click(function () {
            $(this).addClass("saved");
            $(this).html("Remove This");
        });

Upvotes: 0

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

$('a').click(function(){
    $(this).addClass('saved');
    $(this).text('Remove This');
});

Fiddle Demo

Upvotes: 0

Zeth
Zeth

Reputation: 875

Are you trying to do something like this?

http://jsfiddle.net/a6vjxy6c/2/

$("a").on("click", function(e) {
    e.preventDefault();
    if ($(this).hasClass("saved")) {
     $(this).removeClass("saved");
        $(this).html("Save This");
    }
    else {
     $(this).addClass("saved");
        $(this).html("Remove This");
    }

});

Upvotes: 3

Related Questions