Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Target all elements with val less than 1

I have multiple elements in the dom with a class of .blockbadge if the value of any .block-badge is 0 then I want to add a class to that element in order to style it differently.

My JS adds the class to all of these elements if anyone of them equal 0. How do I make it only affect those elements which equal 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');
}
like image 372
Clinton Green Avatar asked Feb 17 '16 22:02

Clinton Green


4 Answers

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

You could use filter() method instead.

Description: Reduce the set of matched elements to those that match the selector or pass the function's 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>
like image 115
Zakaria Acharki Avatar answered Sep 30 '22 14:09

Zakaria Acharki


Like this

   $('.block-badge').each(function(){

    if(parseInt($(this).html()) ===0){

    $(this).addClass('zero');
    }


    });
like image 23
The Process Avatar answered Sep 30 '22 14:09

The Process


You could use the jQuery :contains selector for that specific markup

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

it won't work if any other elements contains a zero, like 10, 101 etc. so if you need only 0, use a filter

FIDDLE

like image 29
adeneo Avatar answered Sep 30 '22 15:09

adeneo


Try using .text(function(index, originalText) {}) where this is current element within collection , originalHtml is 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/

like image 29
guest271314 Avatar answered Sep 30 '22 14:09

guest271314