add axax return from jQuery call to existing class in <i> tag

Hi all

Not great on jQuery and after something quite simple.

Upon clicking the anchor contents (<a href="#" id="favourite">) below I want to add a class to the fontAwesome icon which is what is coming back from the AJAX call to ($.ajax({url: "/utilities/favourite/", async: false, success: function(result){

For this basic example it returns either "green" or "red", simple as that

How can I get it to add this returned text to <i class="fas fa-heart"></i> please


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="" >
<script src=""></script>
<style>.red { color:#F00;}</style>
<a href="#" id="favourite">
    <div class="profileHeaderActionButton _icoFavourite">
        <i class="fas fa-heart"></i>
        <span class="hideMobile">Favourite</span>
			$.ajax({url: "/utilities/favourite/", async: false, success: function(result){
				$( "div ._icoFavourite i" ).addClass(result);

Open in new window

Neil ThompsonSenior Systems DeveloperAsked:
Who is Participating?
Julian HansenCommented:
First up don't use async: false - that is a very bad practice.
AJAX by nature is meant to be Asynchronous - you need to code your application to be async aware rather than forcing the AJAX call to be synchronous.

Next your code is almost correct just remove the space between div and ._icoFavourite.
div ._icoFavourite => means find the child elements of all div's where the child has the class _icoFavourite
div._icoFavourite  => means find the div with the class _icoFavourite

Additionally use the .then() on the returned Promise to handle the callback rather than success.

Finally, you can use $(function() as a shortcut instead of $(document).ready(function()
They are functionally the same thing and the former requires less typing.

Here is the updated code
      url: "/utilities/favourite/"
      $( "div._icoFavourite i" ).addClass(result);

Open in new window

Working example here
Neil ThompsonSenior Systems DeveloperAuthor Commented:
Thanks for the code and great explanation Julian, greatly appreciated.
Julian HansenCommented:
You are welcome.
Neil ThompsonSenior Systems DeveloperAuthor Commented:
another related one just going up now
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.