Change name of a link after user clicks on it

I would like to change the text of an <a> element when the user clicks on it. The code that I’ve written is only “half” working:


$('#linkid').click(function() {
	if ($('#linkid:contains("text1")')) {
		$('#linkid').html('text2');
	} else {
		$('#linkid').html('text1');
	}
.
.
.

Initially the text of the <a> element is “text1”.

When I click on it the text is correctly changed to “text2”. But if I click on it again, the text doesn’t change back to “text1”, it remains “text2”.

What am I doing wrong?

Hi,

Try doing it like this:


$('#linkid').click(function() {
  this.innerHTML = (this.innerHTML == 'text1') ? 'text2': 'text1';
});

It sounds like the condition is always true, try alerting to see what’s returned.


$('#linkid').click(function() {
  alert($('#linkid:contains("text1")'));
}

You want to prevent the amount of lookups using the $() function in your code.
Get an element with it once, then test what you want against it.

The jQuery selector you are using always returns a jQuery object, even if that object contains no matching elements.
So, in the if condition, you need to check that the length of the jQuery object is greater than 0, to ensure that you properly catch a failed match.

However, there is a less expensive and possibly more readable way to perform the check, and that is to test the html content of the element itself.
$(‘#linkid’).html() === ‘link1’

You can also use the this keyword in the function to refer to the clicked link, so your code could instead look like this:


$('#linkid').click(function() {
    if ($(this).html() === 'text1') {
        $(this).html('text2');
    } else {
        $(this).html('text1');
    }
    ...
});

You could also use a ternary operator to specify what content to use.


$('#linkid').click(function() {
    var linkText = ($(this).html() === 'text1') ? 'text2' : 'text1';
    $(this).html(linkText);
    ...
});

Thank you :slight_smile:

Thank you, it worked :wink:

I have just one question: you wrote that “The jQuery selector you are using always returns a jQuery object, even if that object contains no matching elements.” You mean :contains?

I mean:
$(‘#linkid:contains(“text1”)’)

Even testing just $(‘#garbage’) when no garbage identifier exists would test as true, because $() doesn’t return an array, it returns an object.
And we all know that javascript compares objects in strange ways.
Some info about that is:

If an object is compared with a number or string, JavaScript attempts to return the default value for the object.


$('#garbage').toString() // [object Object]
[].toString() // ""

jQuery also formalised their empty sets in 1.4
jQuery() – jQuery API

Understood :wink: