How to toggle HTML text of an anchor tag using jQuery? I want an anchor that when clicked the text alternates between Show Background
& Show Text
In most cases you would have more complex behavior tied to your click event. For example a link that toggles visibility of some element, in which case you would want to swap link text from "Show Details" to "Hide Details" in addition to other behavior. In that case this would be a preferred solution:
$.fn.extend({
toggleText: function (a, b){
if (this.text() == a){ this.text(b); }
else { this.text(a) }
}
);
You could use it this way:
$(document).on('click', '.toggle-details', function(e){
e.preventDefault();
//other things happening
$(this).toggleText("Show Details", "Hide Details");
});