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

conceal elements created with JQuery within an AJAX function

Is it possible to use jQuery and the $.ajax() method to submit a form, displaying only the result while hiding other elements on the page? I am looking to add a conditional in the Ajax method that will show the result if successful, hiding certain elements ...

Disabling scrolling on body while scrolling a superimposed element

I am working on creating a dynamic image gallery for browsers that support Javascript. The gallery consists of thumbnails that lead to full-size photos displayed in a table layout, complete with navigation links and captions. This table is centered using f ...

Styling jQuery Draggable and Droppable <li> elements

I am facing a challenge with my drag and drop functionality using jQuery. While the drag drop feature works perfectly, I need to display two separate pieces of information from a database on each "li" item in different styles. My goal is to include a "tra ...

Storing a JavaScript variable into a JSON file to preserve data

Is it possible to save data from variables to a JSON file? var json_object = {"test":"Hello"} $.ajax({ url: "save.php", data: json_object, dataType: 'json', type: 'POST', success: ...

Is there a way for me to retrieve a variable from outside a function?

I'm trying to access a variable outside of the function in Next.js. I want to retrieve the 'name' from the data object after making an API call. let getDetail = async () => { let body = { code: '12', provider: & ...

What is the best way to ensure that text stays aligned perfectly next to an

There seems to be a problem with my CSS. The text in the <li> tag is appearing below the line of the icon. How can I resolve this issue? I want the text to be vertically centered on the line. This seems to happen when I use the ::before selector with ...

Executing a function every time a prop is updated within the component

I have a prop named transcript in one of my components. Whenever I speak a voice intent, it gets updated. I want to execute a function every time the transcript changes and pass the transcript as an argument. In this code snippet, I attempted to use an On ...

Creating specialized validation for numeric fields in Angular2

Attempting to implement custom validation in Angular 2 has been a challenge for me. I have followed the necessary steps based on my understanding, but still struggling to get it working. import { FORM_DIRECTIVES, AbstractControl, ControlGroup ,FormBuilder ...

The browser is throwing errors because TypeScript is attempting to convert imports to requires during compilation

A dilemma I encountered: <script src="./Snake.js" type="text/javascript"></script> was added to my HTML file. I have a file named Snake.ts which I am compiling to JS using the below configuration: {target: "es6", module: "commonjs"} Howeve ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

Add a captivating backdrop to a div element

So I have this unique HTML element that showcases a large headline with two decorative lines on either side, extending to the full width of the element. However, I now have a requirement to display some text as a background behind this element. The issue ...

Tips for preventing recursion when utilizing scrollIntoView() in a scroll event handler

My goal is to break down my website into screen-sized sections that automatically scroll to the next section when a user begins scrolling. I attempted to accomplish this by using the following code: $(window).scroll(function() { getElementToScroll().s ...

conceal only a few HTML elements

When a user enters text into my comment box, it is saved in the database with additional formatting. For example: aa @Martins <aabb> The saved version in the database looks like this: aa <span class="highlight" contenteditable="false">@Marti ...

Transforming the navigation menu using CSS, HTML, and jQuery

One challenge I am facing involves creating a menu similar to the one on http://edition.cnn.com/. I want the clicked button in the menu to receive focus, while the others lose it. Despite trying various methods, I have not been successful. Can someone off ...

Having trouble getting CSS hover to work on hidden elements?

I am having trouble getting the rollover effect to work correctly on this page, and I can't seem to figure out what's causing the issue. My CSS is quite basic: open{visibility:hidden;} open:hover{visibility:visible;} If you would like to take ...

Unable to change background-image as intended

Here is an example of my HTML code with an initial background image: <div id="ffff" style="width: 200px; height: 200px; background-image: url('/uploads/backroundDefault.jpg')">sddsadsdsa<br>dffdsdfs</div> Everything seems to b ...

The Struts2 JSON response received through the $.getJSON method is showing an unexpected undefined result

Attempting to retrieve a String value from an action class using the $.getJSON method, but receiving an output of undefined. Below are the code snippets that have been tested: Script: $(function() { $("#newPostionFormID").submit( ...

Show information from mysql in a dual-column format

I am pulling data from a single table in mysql, currently displaying it in one column. I want the data to be displayed in two columns next to each other. You can check out the results at www.urimsopa.com Here is my current code: $results = $mysqli->qu ...

400 Error: Frustrating AJAX POST Request Woes

Attempting to send data to a controller using the POST method with jQuery AJAX. Below is the code being used: $('#save_new').on('click', function () { var category_name = $('#new_category').val(); ...

Refresh the page to verify if the user has successfully established a connection with PhoneGap through AngularJS

I am currently developing an app using PhoneGap. I have successfully implemented a feature to check if the user is connected to the internet or not. However, if the user is not connected, I would like to provide a button for them to click on in order to re ...