Top method for utilizing jQuery to locate, sift through, and implement CSS classes

Let's consider the following scenario:

<span class="foo">7</span>
<span class="foo">2</span>
<span class="foo">9</span>

We want to assign a CSS class of 'highest' to 'span.foo' with value greater than 7, a CSS class of 'medium' to values > 4 and <= 7, and a CSS class of 'lowest' to values <= 4.

Here is an example of the desired result:

<span class="foo medium">7</span>
<span class="foo lowest">2</span>
<span class="foo highest">9</span>

Is this a situation where finding and filtering data is necessary? It seems like a common problem, but I am struggling to find the most efficient way to solve it. Thank you!

Answer №1

$(".bar.favorite").each(function(){
  var value = parseInt(this.innerHTML, 10);
  if (value > 7)
    this.className += " top-rated"; 
  else if (value <= 4)
    this.className += " bottom-ranked"; 
  else
    this.className += " average-rating"; 
});

Answer №2

One way to achieve this is by using the find/filter method, but another more convenient option would be to utilize the each method:

$('span.bar').each(function(){
    var $this = $(this),
        value = parseInt($this.html(), 10);

    if (value > 8) {
        $this.addClass('highest');
    } else if (value <= 5) {
        $this.addClass('lowest');
    } else {
        $this.addClass('medium');
    }
});

Answer №3

$(".bar").each(function()
               {
               var block=$(this);
               var num=parseInt(block.text());

                if(num>7)block.addClass("top")
                    else
                if(num>4 && num<=7)block.addClass("middle");
                   else {
                       block.addClass("bottom");
                   }                  
               });

Check it out here: http://example.com/jsfiddle123/

If you prefer using filters, even though they may be less efficient:

$('.bar').filter(function(index) {
  return parseInt($(this).text())>7
      }).addClass("top");

$('.bar').filter(function(index) {
  return (parseInt($(this).text())>4 && parseInt($(this).text())<=7)
}).addClass("middle");

$('.bar').filter(function(index) {
  return parseInt($(this).text())<=4
}).addClass("bottom");

Here's an example: http://example.com/jsfiddle456/

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

Using jquery to update the overall quantity of likes

Utilizing jquery, html, and php, I have successfully implemented a like button on my page. However, I am currently facing an issue with displaying the total number of likes without refreshing the page. Upon clicking the like button, the jquery and php scr ...

Array contains a copy of an object

The outcome I am striving for is: dataset: [ dataset: [ { seriesname: "", data: [ { value: "123", }, { value: &q ...

Having trouble customizing the Material UI button in React?

For a recent project, I utilized the older version (v1) of Material UI to ensure compatibility with Node 10.8. In order to implement a round button, I referred to this demo. The round mini button functioned perfectly without any applied themes. <Button ...

Divs that are 30% of their parent's width will not align vertically and will not fit in a parent div that is 100% width

I am attempting to vertically center the three child-divs <div class="section"> as 3 rows in one column within <div class="container_page_2">. When I refer to vertical alignment, I mean having an equal distance between the top of the page and ...

Delete a particular table while utilizing $.fn.DataTable.tables()

On a single page, I have several tables that need to be removed when the user decides. My approach was to utilize let table = $.fn.DataTable.tables() table[i-1].destroy(); This code is aimed at obtaining an array of all the tables and subsequently destroy ...

What are the best ways to engage with a div element using keyboard shortcuts?

Is it possible to enable keyboard shortcuts for interacting with div elements? I am working on a project tailored for seniors who may have difficulty using a mouse. Is there a way to utilize keyboard shortcuts to click on divs and access their contents? H ...

Attach an event listener to a class, then use the removeEventListener method to detach the listener and eliminate any remaining references, ensuring proper functionality of the

When creating a class in JavaScript, a normal function returns the class object. However, events return the event object and the class object is lost: function class(a){ this.name=a; document.addEventListener('click',this.click,false); xhr.add ...

Replicate the ctrl+/- function through coding

While browsing with your browser, you have the ability to adjust the font size by using CTRL + + or CTRL + -. Is there a way to replicate this functionality through code, such as with JavaScript? I am looking to add buttons on my website that allow users ...

Apologies, but Discord.js is unable to access the property "user" of a null object

I am facing a perplexing issue that I cannot seem to wrap my head around. The function works perfectly on one server but fails on another. Below is the snippet of code in question: const user = message.author; let servericon = message.guild.iconURL; let se ...

Encountered an import error when using "npm run build", but it runs successfully with "npm start"

My React app is running smoothly with npm start, but I encounter an error when trying to build it using npm run build. The error message I receive is: `Creating an optimized production build... Failed to compile. Attempted import error: './parseq-lan ...

Adjust the content column in the form to be mobile-friendly

Currently, I am coding in PHP and using Bootstrap. In my project, there are two columns - the LEFT column displays text, while the RIGHT column contains a form: Presently, when viewing on desktop, both columns are visible. However, on mobile devices, ...

Angular code causing an unexpected blank page to be printed again

Trying to display the content of my HTML page is proving to be a challenge. I've been utilizing angularPrint, but an issue persists in the form of a second blank page appearing in the preview alongside the actual content. Eliminating this unwanted sec ...

Utilize Boolean operators such as AND, OR, and NOT to locate specific keywords within a text, mirroring the search capabilities

Is it possible to perform Google-style searches in strings using operators like "or", "and" and "not" with regular expressions? For instance, I aim to search for the words "Javascript", "PHP" and "Perl" within a given string in these ways: Javascript an ...

Improving the layout and size of text within input fields

How can we adjust the input text positioning to the right so it's not directly against the edge? Is there a way to move 'searching' 5px to the right? ...

NextJS was throwing a warning at me, while Firebase hosting was giving me an error regarding the absence of unique keys for children in lists, even though I

I've been troubleshooting this warning for quite some time, but I can't seem to resolve it. The warning reads as follows: Warning: Each child in a list should have a unique "key" prop. Check the top-level render call using <ul>. ...

Can values be manually inserted into session storage for the purpose of local testing?

I typically work on my local eclipse and local IDEs such as Sublime Text, using XAMPP locally for development. Since local code does not involve authentication and other complex aspects, I am considering manually injecting session storage values into my we ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Converting a String to an Integer in JavaScript

I'm having trouble printing the sum in this code // 1. create variables // 2. input numbers into variables [but they are strings] // 3. unable to print the sum // Variables let num = [""]; let num22 = [""]; // Add new number to num ...

if else statement fails to work in ajax-based login form

I tried to create the code below by referencing processes.php, submit form, and ajax from various sources on the internet. However, my code doesn't seem to be working properly. proccess.php <?php session_start(); ini_set('display_errors&apos ...

Use a spy to mock a component method using karma and jasmine

Encountering this error message during testing: ERROR: 'Error during cleanup of component' The issue stems from the following code snippet : ngOnDestroy(){ methodCallToMock() } To address this, I need to mock the methodCallToMock() functi ...