How to apply unique styles to multiple elements with the same class using jQuery?

How can I add different classes to multiple div elements with the same class based on their content?

<div class = "flag"> Yes </div>
<div class = "flag"> No </div>
<div class = "flag"> Yes </div>
<div class = "flag"> Yes </div>
<div class = "flag"> No </div>

To style them in CSS:

.yes {
   color: green;
}

.no {
   color: red;
}

I attempted the following jQuery code, but it is not working as intended:

$(".flag").each(function(){ 
    if($(this).text().trim() == "Yes") {
        $(this).addClass("yes");
    } else {
        $(this).addClass("no");
    }
});

Answer №1

A few issues need to be addressed in the code:

  • Make sure to select only the specific .flag element within the loop iteration by using the this keyword.
  • Note that JavaScript is case sensitive, so ensure that you are comparing the content correctly (e.g., compare "Yes" not "yes").
  • The content may have leading or trailing whitespace that needs to be removed for accurate comparison. You can utilize the trim() method for this purpose.

$(".flag").each(function() {
  if ($(this).text().trim() == "Yes") {
    $(this).addClass("yes");
  } else {
    $(this).addClass("no");
  }
});
.yes { color: green; }
.no { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="flag"> Yes </div>
<div class="flag"> No </div>
<div class="flag"> Yes </div>
<div class="flag"> Yes </div>
<div class="flag"> No </div>

Alternatively, a more concise approach is possible by using an implicit loop with addClass() and a ternary expression:

$(".flag").addClass(function() {
  return $(this).text().trim() == "Yes" ? 'yes' : 'no';
});
.yes { color: green; }
.no { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="flag"> Yes </div>
<div class="flag"> No </div>
<div class="flag"> Yes </div>
<div class="flag"> Yes </div>
<div class="flag"> No </div>

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

Utilize React to showcase all stored items in localStorage in a Material UI List

I have a storage system with multiple items stored in it. I am looking to retrieve all of them and showcase them using a <ListItem> from Material UI. This is my current code snippet: function saveItem(key, value) { localStorage.setItem(key, value) ...

Challenges arising with the express search feature

Currently, I am in the process of developing an API for a to-do application. I have successfully implemented the four basic functions required, but I am facing some challenges with integrating a search function. Initially, the search function worked as exp ...

Saving MongoDB query results to a file using the built-in Node.js driver

I have been attempting to save the output of a MongoDB query to a file using the native Node.js driver. Below is my code (which I found on this post: Writing files in Node.js): var query = require('./queries.js'); var fs = require('fs' ...

Tips for successfully passing an array containing an object to an AJAX action

I am facing an issue with passing an object in AJAX that has a list of properties to my action. The problem is that the list always ends up being null. How can I resolve this? Below is the code snippet: Class Definitions : public class SaveProduct { ...

What is the best way to transfer the API Response Time from one Fetch function to a separate asynchronous function?

After successfully obtaining the API Response Time (duration) using the 'makeAPICall' function, I am now faced with the task of passing this duration variable value to another asynchronous function. Can anyone assist me in finding a solution to a ...

Using a forward slash in the path for the href attribute in a CSS link within an ejs file

Image 1: Configuring express.static for the public folder Image 2: Adding href="/app.css" in post.ejs file Image 3: Final result While experimenting with using /app.css and app.css in the post.ejs file, I noticed that the outcome was consistent with th ...

Trouble with setting the color attribute using setProperty in a GXT text area

Help needed in dynamically changing the font color of a text area from the color menu. Existing attempts to change it have not been successful. Can someone provide assistance? final ColorMenu fontColorMenu = new ColorMenu(); fontColorMenu.getPalette().a ...

Is it possible for jQuery UI Autocomplete to utilize values from various input fields simultaneously?

I've hit a roadblock with this code and it's been giving me trouble for some time now. Here is the current state of my auto-complete script: jQ19(function(){ // minLength:1 - how many characters user enters in order to start search jQ19 ...

What steps are involved in importing remark-gfm into next.config.js?

I am interested in incorporating MDX into next.js with the remark-gfm plugin. After discovering the Next.js Docs on MDX, I decided to follow their guidelines and added an import statement. // next.config.js import remarkGfm from 'remark-gfm;' co ...

Can the name of the Grunt task target be utilized within attributes?

I have implemented the grunt-replace task to make some content changes in the index.html file. However, I am looking for a way to avoid repeating code unnecessarily. The code snippet below is just an example of what I am trying to accomplish: replace: { ...

Adjusting the vertical dimension of an Angular 17 Material Dropdown Field?

Check out this demo where I'm exploring ways to decrease the height of the select field. Here's the code snippet: <mat-form-field appearance="outline"> <mat-label>Toppings</mat-label> <mat-select [formControl]=& ...

When the parent element has a fixed position, the child element will no longer maintain its floating property

I'm currently working on a fixed navigation panel that sticks in place while scrolling down. Here is the code I have so far: <header> <a class="logo" href="/">Logo_name</a> <nav> <a href="#">Menu_1</a& ...

Maintain the div height as the image loads

Is there a way to prevent the collapse of the .img-container while an image is loading? Currently, when the image takes a few seconds to load, the container collapses and only expands to full height once the image has loaded. I would like the container to ...

HTML5 Applications with Intel XDK

I'm currently working on an HTML5 application using Intel's XDK platform for building in Android. However, I'm facing an issue where the application crashes when the keyboard pops up upon entering text. Can anyone provide assistance with thi ...

FusionCharts Gauges may share similar code, but each one produces a unique output

Currently, I am developing a project that involves creating a dashboard with 3 gauges. These gauges are enclosed in bootstrap cards with a column value set to 4. In the layout of the dashboard, these 3 cards are positioned next to each other. I have succe ...

What is the best way to connect specific nodes to the edge of a canvas in cytoscape and create perfectly straight lines?

In the center column of my article, I have two graphs created with cytoscape showing "ancestors" and "descendants" on the sides. I am interested in displaying the connections ("edges") from the articles in the final generation of "ancestors" to the articl ...

Is the callback for a request always invoked?

When using the npm module request, I often encounter situations where some requests are not called back, leading to various issues. This has raised a question in my mind - is it expected for the request function to always callback? For instance, if my req ...

Can we disable hydration warnings for all nested children within a component in NextJS?

Note: I am currently using NextJS 14, but I suspect this issue also exists in NextJS 13. I have created a ThemeToggle component that utilizes the next-themes package. Even if I develop my own version of next-themes using React Context or another state man ...

Encountering an unusual hash code when implementing Google Tag Manager in a Next.js project was

I am currently using Next.js and have added Google Tag Manager through a script <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var ...

The jQuery variable appears to be failing to update after the completion of an ajax request

Every time I click the load more button, it is supposed to display 10 new results. However, the offset value does not update and as a result, I keep seeing the same set of 10 results repeatedly. $("#loadmore_timeline").on("click",functi ...