Having trouble making changes to FontAwesome CSS using jQuery?

I am currently working on an MVC project where I am using Ajax to update a specific section of a View that contains a FontAwesome 5 icon. The FontAwesome icons are set using CSS classes, so my initial assumption was that it would be simple to remove and add the necessary CSS for the icon. However, when attempting to make the CSS change through jQuery, the CSS is not being set. The add/remove class functions as expected for the regular CSS class I am changing, but not for the FA class valid-icon.

Here is the original HTML code:

@if (Model.VALID_FLAG == "Y")
{
    <div class="validation__text-success" id="valid-flag>
        <i class="fas fa-check-circle" id="valid-icon"></i> Yes
    </div>
}
else
{
    <div class="validation__text-danger" id="valid-flag>
        <i class="fas fa-times-octagon" id="valid-icon"></i> No
    </div>
}   

This is the jQuery script used in the Ajax call:

var $html = $(response);
if ($html.hasClass('alert-success')) {
    $("#valid-flag").text('Yes');
    $("#valid-flag").removeClass().addClass('validation__text-success');
    $("#valid-icon").removeClass().addClass('fas fa-check-circle');
}
else if ($html.hasClass('alert-danger')) {
    $("#valid-flag").text('No');
    $("#valid-flag").removeClass().addClass('validation__text-danger');
    $("#valid-icon").removeClass().addClass('fas fa-times-octagon');
}

Answer №1

The text() method is used to replace all text content, including the icon element.
If you prefer to replace both the icon element and text label simultaneously, you can use the html() method.

An alternative approach involves modifying a specific text node of the element by utilizing contents(). This concept was shared in an answer by charlietfl.

It should be noted that the example below intentionally includes duplicate IDs for illustrative purposes. This demonstration underscores the limitation that you cannot alter the HTML code received as a response.

var response = [
  `<div class="alert-success" id="valid-flag">
     <i class="fas" id="valid-icon"></i> ???
   </div>`,
  `<div class="alert-danger" id="valid-flag">
     <i class="fas" id="valid-icon"></i> ???
   </div>`
];

function processResponse(response) {

  var $html = $(response);

  if ($html.hasClass('alert-success')) {

    $html.contents().last()[0].textContent = 'Yes';
    $html.removeClass().addClass('validation__text-success');
    $('#valid-icon', $html).removeClass().addClass('fas fa-check-circle');

  } else if ($html.hasClass('alert-danger')) {

    $html.contents().last()[0].textContent = 'No';
    $html.removeClass().addClass('validation__text-danger');
    $('#valid-icon', $html).removeClass().addClass('fas fa-frown');

  }

  $('body').append($html);

}


$.each(response, function(i, v) {
  processResponse(v);
});
.validation__text-success {
  background-color: lightgreen;
}

.validation__text-danger {
  background-color: pink;
}

#valid-icon {
  margin: 0 .5em 0 0;
}
<link href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The use of backdrop-filter results in artifacts appearing in rounded corners

I am experiencing an issue with a CSS animation where I have an element that fades and child elements with a backdrop-filter to blur the background in Safari. There are two specific problems: The element's rounded borders are showing dark shadow ...

What is the best way to implement this design using CSS flexbox?

I'm working on designing a simple layout that looks like this: https://i.stack.imgur.com/oCzyV.png Currently, I have the following HTML structure with some variations in class names and additional markup within each element: <div class="site ...

The color of the text changes based on its alignment

Utilizing style sheets and attribute selectors, create styles that will change the color of text displayed on the page based on its alignment (e.g. left-aligned text in blue, right-aligned text in green). Additionally, text within h2 tags should have color ...

The concept of CSS sprites and managing background positions

I have been working on integrating a star-rating widget that requires the use of a sprite file. The sprite file I am using looks like this: https://i.stack.imgur.com/ZSMMj.png This is how my HTML is structured: HTML <span id="star-ratings" class="c ...

Unexpected behavior found in certain parts of jquery due to the implementation of Ajax

Every time I try to use the ajax code on the same page or an external .js file, it seems to cause issues and prevents other parts of the code (jquery) from functioning properly. The ajax should only trigger when clicking on a specific li element with the c ...

I'm facing an issue with the footer and header that is preventing me from properly positioning any content on the website

When attempting to include an h3 element on the website, it remains stuck at the top. I have tried using CSS properties like position, top, and left but it does not respond to them. Additionally, I experimented with a gallery template from w3schools to see ...

Is there a way to display a button and text upon hovering over an image without using JQuery?

On my current WordPress project, I am faced with the task of creating a gallery that displays text and a button when users hover over an image. I have attempted to use a:hover but have only been able to make limited modifications. Can anyone provide guid ...

When there is no content in the responseText, AJAX will display an error

I've encountered an issue while trying to fetch data using AJAX. The problem lies in receiving an empty responseText. Here's the code I'm working with: JavaScript: function getFounder(id) { var founder = ""; $.ajax({ ...

Phonegap integration with Web services

My index.html file includes an ajax call to a webservice (ASP.NET) that functions properly when deployed on the bigrock server with my domain. $.ajax({ type: "POST", url: "myurl/mywebservice.asmx", contentType: "application/json; ...

PHP script output continuously responded with AJAX

Encountering an issue with the AJAX response from my PHP script... I've set up a "Status" div to display the response of the PHP script. It currently only shows the response once the entire script has finished, but I would like it to show each echo " ...

Experiencing issues with your Jquery Slider?

An issue arises while utilizing the jquery slider in my aspx page that is associated with a master page. The error message received is: The state information is invalid for this page and might be corrupted. Description: An unhandled exception occurred du ...

Get the QR code canvas image with a customized background by downloading it

I am having trouble with downloading a QR code canvas image with a background. The download works fine, but my device is unable to scan the code properly due to an incomplete border. I need to add a white background behind it to make it larger. Current im ...

Align the elements of the contact form to the opposite sides

I am experiencing an issue with my contact form where all elements are flowing horizontally instead of vertically. I would like everything to be floated to the left and aligned vertically, except for the "message" box and submit button which should be on t ...

Updating a jQuery variable through an AJAX request

Is there a way to update a variable that is located outside of an AJAX call from an event that is inside this AJAX call? This snippet of code shows that the var units is initially set to metric, but when a selectbox changes (inside the AJAX call), I want t ...

Is there a way to hide a button on this virtual keyboard after it has been clicked?

After creating a virtual keyboard using HTML and CSS, I am looking to implement JavaScript code that will hide a button after it is clicked. Here is the code I have tried so far: function hideButton() { var button = document.getElementById("simple_butto ...

Prevent the tab key from exiting the input field and instead direct it to a designated element on the webpage

I have customized a select menu for user interaction, but I am facing issues with normal keyboard behaviors not working as expected. Specifically, I want to enable tab functionality to navigate to my styled select menu just like when clicking tab to cycle ...

Having difficulty controlling the DOM within an AngularJS template

My website utilizes AngularJS templates, specifically a Single Page Application (SPA). Within one of the templates, I am utilizing a tab control from the AngularUI library named Ui-Tabset. During the rendering process, this control generates a ul element ...

Switch between display modes using a button and CSS media query

I'm trying to find the most effective method for toggling display states on a webpage using a button while also being able to adjust based on screen size. For larger screens, I want to default to a horizontal layout with the option to switch to vertic ...

Placing two texts alongside a logo in a Bootstrap Navbar: Step-by-step guide

As I venture into the world of Bootstrap, I am on a quest to create a Navbar Component similar to this design: https://i.stack.imgur.com/NidKQ.png I attempted to use the Navbar Image and Text code, but encountered an issue where the text would only displ ...

Utilize text hyperlinks within the <textarea> element

I am currently using a textarea to post plain text to a MySQL database table. However, I now wish to add hyperlinks within that text. How can I accomplish this without utilizing any editing tools? ...