NineCattoRules
NineCattoRules

Reputation: 2428

How can I change icon on AJax response?

I have an anchor tag with an icon inside that I want to change it on click. So, using Ajax I tried as below:

HTML

<a id="#pl-esong234" class="social-button-song" title="Add in playlist" onclick="addInPlaylistSongs(234, 1)">
  <i class="ion-plus all-btn-icon"></i>
</a>

JS

function addInPlaylistSongs(track, id) {
    $.ajax({
        type: "POST",
        url: baseUrl+"/requests/manage_playlists.php",
        data: "id="+track+"&playlist="+id+"&type=4&token_id="+token_id, 
        cache: false,
        success: function(html) {
            $('#pl-esong'+track).append('<i class="ion-checkmark all-btn-icon"></i>');
        }
    });
}

I tried also:

//2nd try
$('#pl-esong'+track+' i').after('<i class="ion-checkmark all-btn-icon"></i>').remove();

//3rd try
$('#pl-esong'+track+' i').after(html).remove();

//4th try
$('#pl-esong'+track+' i').replaceWith(html);

I tried to console log on success and everything is correct, the html response is <i class="ion-checkmark all-btn-icon"></i> and the select item is #pl-esong234.

Why I'm not able to change the icon inside my anchor element?

Upvotes: 0

Views: 1527

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

Remove the hash from the id. It is using by the selectors to find the matched tag.

# - used to find by id. . - user to find by class

<a id="pl-esong234" class="social-button-song" title="Add in playlist" onclick="addInPlaylistSongs(234, 1)">
  <i class="ion-plus all-btn-icon"></i>
</a>

and call html().

$('#pl-esong'+track+' i').html('<i class="ion-checkmark all-btn-icon"></i>');

Upvotes: 4

Related Questions