Leveraging jQuery to dynamically load an icon based on the content within a <label> tag

I manage a website that dynamically fetches content from a database, with varying contents for each label. For example, one label may be generated as General:, while another may be generated as TV:. My question is, can jQuery be used to replace the text NAME: with a Font Awesome icon based on the label in the HTML output?

For instance:

<label>TV:</label>

This would transform into:

<i class="fa fa-film fa-2x"></i>

Answer №1

Give it a shot

var items = {
    'ctrl:': 'control',
    'del:': 'delete'
};

$('span').replaceWith(function () {
    var text = $(this).text().trim().toLowerCase(),
        item = items[text];
    return item ? '<i class="fa fa-' + item + ' fa-2x"></i>' : undefined;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css">

<span>CTRL:</span>
<span>DEL:</span>

Answer №2

If you're looking to target specific elements containing certain text, consider utilizing the :contains selector. Check out this resource for more information.

$("span:contains('movie')").html('<i class="fas fa-ticket-alt"></i>');

Answer №3

$(".label:contains('TV')").html('<i class="NEW CLASS"></i>');

Alternatively, if you want to make changes based on a specific id or class within the label, you can do so easily by using:

$("#ID").html('<i class="NEW CLASS"></i>');

$(".CLASS").html('<i class="NEW CLASS"></i>');

Answer №4

One option is to use jQuery to replace them

var symbols = {
    "TV:" : "film"
};

var $labels = $('label');
$labels.each(function(index){
    var symbol = symbols[$(this).text()];
    $(this).replaceWith($("<i>").addClass('fa').addClass('fa-' + symbol).addClass('fa-2x'));
});

Check out this Fiddle for a demonstration: http://jsfiddle.net/x5g2d3rp/

Answer №5

There are several approaches you can take to solve this issue.

Personally, I prefer sending the correct label directly from the server.

If that's not an option, you could utilize the following jQuery script: http://jsfiddle.net/ehdgL6so/

// Optimize for speed by selecting minimal elements
var labels = jQuery('label');

// Iterate through all labels
labels.each(function() {
    // Get individual label element
    var label = jQuery(this);
    // Retrieve content of label (e.g., "TV:")
    var labelContent = label.text();

    // Replace based on label content
    switch(labelContent) {
        case 'TV:':
            // Replace label with <i> element if it contains "TV:"
            label.replaceWith('<i class="fa fa-film fa-2x"></i>');
            break;
        case 'Foo':
            // Replace "Foo" with <i> element
            label.html('<i class="fa fa-film fa-2x"></i>');
            break;
    } 
});

Edit: Alternatively, as suggested by @cforcloud, use a concise form like:

// Note: .html only replaces the string "TV:" without removing the label element from the DOM; use replaceWith to replace the entire element
// http://api.jquery.com/replacewith/
jQuery("label:contains('TV:')").replaceWith('<i class="fa fa-film fa-2x"></i>');

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

Managing Custom CSS Files in Sencha Touch 2 Production Build

Currently, I am in the process of working on a mobile website using Sencha Touch 2. To develop the production build, I utilized Sencha Cmd v3. Upon testing the production version, I noticed that although my custom CSS files are present in the folder struct ...

The SDK generated by AWS API Gateway does not include the JavaScript client file

After setting up my API with the AWS Api Gateway Service, I am now looking to integrate the javascript SDK into a basic webpage. The provided instructions for using the javascript SDK can be found here. However, they mention importing a js file named apig ...

How can I center the window vertically based on the middle of an element?

Hey guys, I need some help with my code. I've been trying to create a button that will shift the window's Y position to center the "Box - 5" div vertically through an onclick event. Basically, I want to make sure the "Box - 5" div is positioned i ...

Achieving a transparent inner box-shadow effect on hover: a step-by-step guide

Is there a way to make the black ring transparent upon hover by changing box-shadow: 0 0 0 5px #000, 0 0 0 10px green to box-shadow: 0 0 0 5px transparent, 0 0 0 10px green? It doesn't seem to be working for me. Any suggestions on how to achieve this ...

Issue with fullcalendar: difficulty displaying events using ajax after clicking 'previous' or 'next' button

I am currently working on creating a calendar using fullcalendar. To retrieve data for the month, I make an external ajax request. Here are the key variables I utilize to render the fullcalendar: eventsJsonArray - used to load all events for the month ...

Sending an Ajax request to the current page results in receiving both the data and the entire

I am looking to implement a form on my website where users can input information and have it sent to a PHP script within the same file. While I understand that separating the PHP into its own file is the best practice, I am determined to make this method w ...

The twelfth child in the sequence is not functioning properly, although the others are working correctly

In my list, I have 12 elements and each element contains a div. My goal is to set different sizes for each div by using nth-child on the li element. However, the configuration for the 12th element does not seem to work correctly compared to the rest of the ...

How can you tell if a specific keyboard key is being pressed along with the CTRL button?

Is there a way to call functions when a specific key is pressed along with the CTRL key (on a Windows system)? While testing for a particular keyCode, I used event.keyCode. I researched the codes assigned to each key and assumed that 17 + 73 would represe ...

The toggle function for the hamburger icon is currently malfunctioning

I am facing an issue with the hamburger icon on my website. The toggle functionality associated with it is not working properly. Even though I have a class named change-1 that should be toggled upon clicking the icon, it is not happening. There are no erro ...

Choose elements with unique identifiers other than those provided by the API

Seeking assistance with Material UI select element and naming dropdown. Have a few questions: 1: My API that populates the dropdown lacks good names. Is it possible to assign names like 'data 1, data 2, data 3...' to the options without manually ...

Issues arise with AJAX post

I have run into an issue with my jQuery and Codeigniter setup while trying to update the database via AJAX. Despite having the following code in place, nothing seems to be happening or getting sent to my controller when the button is clicked... Snippet of ...

Tips for improving the loading speed of Ajax applications

Having an issue with the speed of loading AJAX pages on my main.php and ajx_receipt_sub_detail.php. Looking for suggestions to increase the loading speed of AJAX. Main.php <script src="scripts/jquery-1.11.0.min.js"></script> <script> f ...

Unraveling a Java String with HTML elements into a JsonObject: Step-by-step Guide

Hey there, I have a Java String that was received from an HTTP request and it looks like this: {SubRefNumber:"3243 ",QBType:"-----",Question:"<p><img title="format.jpg" src="data:image/jpeg;base64,/9j/4AAQSkZJRgAB..."></img></p>"} ...

Integrating ajax response with vue.js in a single page with multiple requests

After spending several days delving into Vue.js and its interaction with Laravel, I have hit a roadblock and now find myself questioning two things: Either I lack the expertise to enhance our user experience as desired, or what I am attempting to do is sim ...

What is the most effective method for iterating through a JavaScript array?

Let's discuss an interesting way to work with JavaScript arrays. Consider the array below: const allRows = [ {id: 1, name: Name 1}, {id: 2, name: Name 1}, {id: 3, name: Name 1}, {id: 4, name: Name 1}, {id: 5, n ...

how to forward visitors from one URL to another in a Next.js application

I have an existing application that was initially deployed on , but now I want to change the domain to https://example.com. What is the best way to set up redirection for this domain change? I have attempted the following methods: async redirects() { r ...

Hide the Bootstrap slide menu with jQuery by clicking anywhere on the screen

Here is a Fiddle link: https://jsfiddle.net/r94dq2e4/ I have incorporated a slide-in menu from the left in my website using Twitter Bootstrap version 3. The menu appears when the navbar toggle button is clicked. This is the jQuery code responsible for ...

When using express to serve a static file with sendfile, the route specified is considered as the relative directory rather than its actual location directory

I'm facing an issue with a route in Express router.get('projects/fest', function(req, res, next){ res.sendfile('fest.html', {root: './public'}); }); When accessing localhost:3000/projects/fest, the HTML file is disp ...

Utilizing the correct method for binding checkboxes in Vue JS for effective two-way communication

I am working with data retrieved from a MySQL database where "1" and "0" represent boolean true and false. In my Vue component, I have set these values as shown below: data(){ return { form : { attribute_1 : "1", //attribute 1 is true ...

Matching a regular expression pattern at the beginning of a line for grouping strings

One of my tasks involves working with a markdown string that looks like this: var str = " # Title here Some body of text ## A subtitle ##There may be no space after the title hashtags Another body of text with a Twitter #hashtag in it"; My goal ...