Yeganeh Hajimiri Yeganeh Hajimiri - 1 month ago 9
HTML Question

Change text value in html after append

I create a button with append

var row = '<tr><td><button class="directly-follow btn" text="Follow">Follow</button></td></tr>';
$('.textWord_about> table > tbody').append(row);


I want to change the button text using jquery, by clicking on the button.

This is what am I doing:

$(document).on('click', '.directly-follow', function() {
event.preventDefault();
var $post = $(this);
if ($post.attr("text") == "Follow") {
$post.text('Unfollow');
//do something
}
else{
$post.text('Follow');
//do something
}


the problem is that the line
$post.text('Unfollow')
changes the button text but it does not change the defined text in the html tag(
text="Follow"
). As a result, the functionality does not toggle as I want.(the if is always true!).

How can change the text using jquery?

Answer Source

To change the value of a custom attribute you have to use attr method.

attr method can be used in order to get the attribute value, but also to set the attribute value.

The method gets the value of an attribute for the first element in the set of matched elements or sets one or more attributes for every matched element.

$(document).on('click', '.directly-follow', function() {
event.preventDefault();
var $post = $(this);
if ($post.attr("text") == "Follow") {
    $post.text('Unfollow');
    $post.attr('text','Unfollow');
 }
 else{
    $post.text('Follow');
    $post.attr('text','Follow');
 }