Step-by-step guide on replicating the style of a div class

I'm attempting to create a comments counter div that changes color based on the number of comments. If there are 0 comments, the div should be red, and if there are more than 0 comments, the div should be blue. However, I am encountering an issue with JavaScript duplicating the same colors.

$(function () {
    if(parseInt($(".notification-counter").text()) > 0) {
        //$(".notification-counter").hide();
        $('.notification-container').addClass('notification-container2');
    }
});

Check out the code here: http://jsfiddle.net/783h57zy/10/

Thank you for any assistance!

Answer №1

To traverse through each of the divs, you will need to utilize the .each() function along with $(this):

$(function () {
    $('.notification-container').each(function () {
        if (parseInt($(this).text()) > 0) {
            $(this).addClass('highlight');
        }
    })
});

View jsFiddle demo

Answer №2

$(document).ready(function () {
$('.notification-counter')
  .filter(function() {
      return $(this).text() >= 0;
  }).parents('.notification-container')
  .addClass('new-notification-style');
});

View code on jsfiddle

Answer №3

To achieve the desired result, it is important to loop through each element and then modify the class accordingly.

Make sure to make the following changes in your code:

$(function () {
    $(".notification-counter").each(function(){
    if(parseInt($(this).text()) > 0) {
        //$(".notification-counter").hide();
        $(this).parent().addClass('notification-container2');
    }
    });

});

You can view the updated version on this fiddle - http://jsfiddle.net/783h57zy/12/

Answer №4

To properly adjust the styling of your divs, you should iterate through them individually:

Utilize $.each to loop through the div elements.

Refer to '.parent()' to access the parent container div.

Use $(this) to reference the current element being processed.

$(function () {
    $('.notification-counter').each(function () {
        if (parseInt($(this).text()) > 0) {
            $(this).parent().removeClass('notification-container').addClass('notification-container2');
        } else {
            $(this).parent().removeClass('notification-container2').addClass('notification-container');
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="notification-container">
    <div class="notification-counter">200</div>
</div>
<div class="notification-container">
    <div class="notification-counter">0</div>
</div>

Answer №5

With multiple instances of the same class present on the page, it is necessary to iterate through each instance and analyze them individually before making any decisions.

$(function () {

    $('.notification-counter').each(function(){

        if( parseInt($(this).html()) === 0 ) {
            $(this).addClass('notification-container2');
        }

    });

});

See the updated version here: http://jsfiddle.net/783h57zy/14/

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

What steps should be taken to ensure that my nodeJS server can maintain the identity of a specific user?

Currently, I am in the process of building a mobile application that utilizes Flutter for the front-end and NodeJS for the back-end. Progress has been steady, but I have hit a roadblock while trying to incorporate a lottery feature. The idea is for the se ...

The significance of the "$=" or "?=" symbols in lit-element illustrations

I'm struggling to comprehend the purpose of ?= or $= in these two instances: First Example: Lit-Element README <div id="box" class$="${this.uppercase ? 'uppercase' : ''}"> <slot>Hello World</slot> </div> ...

Having trouble with retrieving data from a JSON file through a service in Angular 4? Getting an "unexpected end of input" error?

I've been attempting to retrieve data from a JSON file stored in the assets folder, but all I keep encountering are errors. heroes.service.ts getPeopleData(): Observable<people[]>{ return this.http.get<people[]>('assets/data/someD ...

Issue with Tanstack React Query failing to import

Attempting to integrate tanstack react query into my current project to handle state management has proven challenging. Following a tutorial on using react query with nextjs 13, I thought I was following it correctly. However, I encountered various import ...

The css fails to display properly upon the page being reloaded using a button

While diving into the world of learning React JSX, I've encountered a perplexing issue. After clicking the load button, the page redirects correctly but the CSS styling I've implemented fails to display. Here is the HTML code snippet: <!DOCTY ...

Getting directions using the node-googlemaps module in node.js can be achieved by following these steps

For the past day, I've been attempting to make progress with this Node.js Google Maps directions example, but so far, no success. Every time I run it, I keep seeing ·· √ OK » 2 honored (0.848s). I've previously asked a similar question on U ...

Converting Jquery to Vanilla JavaScript for Bootstrap Scroll Function

I have been attempting to convert this jQuery code to vanilla JavaScript, but I am struggling with it. Can anyone assist me? Here is the jQuery code. The intended functionality is for an effect to toggle as I scroll, but it currently isn't working. I ...

I encountered a blank page issue when incorporating ui.bootstrap into my controller within Angular

After attempting to utilize angular bootstrap in my project, I encountered an issue where adding the dependency in my controller and starting the server with grunt serve resulted in a blank page. Take a look at the bower components in the screenshot provid ...

Issues arising from parsing JSON with JQuery

The Json data below is causing a parse error in JQuery: [{"label":"75001","value":"75001"}, {"label":"75002","value":"75002"}, {"label":"75003","value":"75003"}, {"label":"75004","value":"75004"}, {"label":"75005","value":"75005"}, {"label":"75006","value ...

"Items within mui Grid do not properly align within the Grid container

I'm struggling to fit two large Grid items inside a Grid container. The Grid container needs to be 100% of the screen's height (or parent container) Grid items are large and need to fill the container while remaining scrollable Image #1 shows t ...

Include a proximity button onto the tabs

Currently, I'm diving into learning Bootstrap and one thing I'd like to implement is having an x next to each tab name for easy closing: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__ ...

Unspecified response from Axios in NodeJS API when logging to console

I have been working hard to get this code functioning properly. const axios = require('axios'); let bodyapi = axios.get('the API is located here') console.log(bodyapi.data) <- displaying as undefined let body = bodyapi.data console. ...

Tips for preserving scroll position within a division following the redisplay of a division in Vue.js

Within my Laravel and Vue project, I have set up a feature to display posts in a scrollable area. This area is only visible when the 'showFeed' variable is true. <div v-show="showFeed" class="scroll-container" v-scroll=&quo ...

When attempting to install material UI in my terminal, I encounter issues and encounter errors along the way

$ npm install @material-ui/core npm version : 6.14.4 Error: Source text contains an unrecognized token. At line:1 char:15 $ npm install <<<< @material-ui/core CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException ...

Vue 3 has officially deprecated the use of ::v-deep as a combinator. Going forward, please utilize ::v-deep(<inner-selector>) instead

Recently, an error message has been popping up in Vue 3 regarding the use of ::v-deep. The warning states that using ::v-deep as a combinator is deprecated. Instead, it recommends using ::v-deep(<inner-selector>) Here is an example of the CSS ...

Eliminate Element Node Issue

I'm trying to remove a newly generated element using this code, but it doesn't seem to be working. I checked in firebug and there are no JS errors appearing. $('.popular-list li a').on("click",function() { var stuff = $(this).text( ...

Retrieving the smallest and largest values of a Django model attribute within a template

My data model looks like this: class Integer(models.Model): integer_value = models.IntegerField(default=0) current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00) share = models.IntegerField(default=0) market = mo ...

Understanding the outcomes of CSS media queries

I'm currently grappling with CSS media queries for a mobile-centric webpage. My main objective is to maintain consistent font sizes on the page, regardless of device physical size and resolution specifications that may vary. However, I am finding that ...

Guide on moving the parent <div> at an angle within an AngularJS custom directive

The code snippet below demonstrates the functionality of dynamically generated ellipse elements as they change color based on an array. I have been experimenting with updating the style property of the parent div element within a custom directive. This in ...

fileuploader with clipboard functionality and easy drag-and-drop feature using HTML and JavaScript

I am in need of a file uploader that can be implemented using HTML and JS. My goal is to have it work on multiple platforms, specifically Google Chrome, FireFox, and IE9+, with the capability of copying and pasting screenshots as well as dragging and dropp ...