JQuery: set all elements with a shaft less than 1

I have several elements in dom with the class .blockbadge , if the value of any .block-badge is 0, then I want to add the class to this element so that its style is different.

My JS adds a class to all of these elements if any of them is 0. How to do this, it affects only those elements that are zero?

HTML

 <span class="block-badge">1</span> <span class="block-badge">0</span> // this element should have the class 'zero' added <span class="block-badge">4</span> 

Js

 var blockBadgeVal = $('.block-badge').val(); if (blockBadgeVal < 0) { $('.block-badge').addClass('zero'); } 
+6
source share
4 answers

The code in OP will not work because $('.block-badge').html() will return the html of the first element with the block-badge class, so in this case it returns line 1 , you should parse the return value and then compare it from 0 .

You can use filter () instead.

Description: Reduce the set of matched elements to those that match the selector or pass a function test.

 $('.block-badge').filter(function(){ return parseInt($(this).text())==0; }).addClass('zero'); 

Hope this helps.


 $('.block-badge').filter(function(){ return parseInt($(this).text())==0; }).addClass('zero'); 
 .zero{ color: red; font-weight: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="block-badge">1</span> <span class="block-badge">0</span> <span class="block-badge">4</span> 
+6
source

Like this

  $('.block-badge').each(function(){ if(parseInt($(this).html()) ===0){ $(this).addClass('zero'); } }); 
+3
source

You can use the jQuery :contains selector for this special markup

 $('.block-badge:contains(0)').addClass('zero'); 

it will not work if any other elements contain zero, e.g. 10 , 101 , etc., so if you only need 0 , use a filter

Fiddle

+1
source

Try using .text(function(index, originalText) {}) , where this is the current item in the collection, originalHtml is the current textContent

 $(document).ready(function() { $(".block-badge").text(function(index, originalText) { if (originalText <= 0) { $(this).addClass("zero"); } return originalText }); }); 

jsfiddle https://jsfiddle.net/s2g3zpwr/3/

+1
source

All Articles