Erick
Erick

Reputation: 91

JavaScript change div class on text

I need to change the <div> class if the text more than 0. My code is:

$(function () {
    if (parseInt($(".notification-counter").text()) == 0) {
        //$(".notification-counter").hide();
        $(".notification-container").hide();
    }
});

But this code will just hide the <div> if text is equal to 0. Instead, I need to change the <div> if the text is more than 0. How do I do this?

Upvotes: 0

Views: 91

Answers (3)

danieljkahn
danieljkahn

Reputation: 183

As you specified you want to change the class when the text is "more than 0", you can change your conditional to greater than zero like so..

if(parseInt($(".notification-counter").text()) > 0)

Then you can add a class like so...

$('.notification-container').addClass('newClass');

If you would first like to check for another class for possible removal, you can create an if statement using jQuery's hasClass() then use removeClass() and addClass() accordingly.

Here's an example that adds .new-class to the container when the value is above 0 http://codepen.io/anon/pen/MwXZMq

Upvotes: 2

Antoine Pointeau
Antoine Pointeau

Reputation: 399

You use Jquery, so you have many possibilities to do that, look at their documentation you have the addClass() function, the hasClass() function and the removeClass() function that allow you many things.

And for the easier solution :

$(function () {
if (parseInt($(".notification-counter").text()) != 0) {
    $(".notification-container").addClass("myclass");
}
});

EDIT : if (parseInt($(".notification-counter").text()) != 0)

Upvotes: 0

scniro
scniro

Reputation: 16979

I think you are wanting the .length property. Try the following...

$(function () {
    if ($(".notification-counter").text().length === 0) {
        $(".notification-container").hide();
    }
});

Upvotes: 2

Related Questions