Reputation: 2201
I want to change an element's class using javascript/jQuery if the inner HTML of the element is 0
I tried the code below but it didn't seem to work.
var myElement = jQuery('.thisclass');
for(var i=0; i<myElement.length; i++){
if(myElement[i].innerHTML == ' 0 '){
jQuery('.thisclass').toggleClass('.newclass');
}
}
Can someone guide me through? what am i doing wrong here? is there any simpler way to do it (all with jQuery)
jsfiddle - http://jsfiddle.net/rm5Sp/
Upvotes: 1
Views: 6181
Reputation: 4393
Try this:
$(".thisClass").each(function(){
if ($(this).html() == " 0 ") {
$(this).toggleClass("newClass");
}
});
Upvotes: -1
Reputation: 136
I think you have to trim the inner html content to remove empty and unwanted trailing spaces.
Try this:
$(".thisclass").each(function() {
var thisHtml = $(this).html();
if (thisHtml.trim() == "0") {
$(".thisclass").toggleClass("newclass");
}
});
Upvotes: 0
Reputation: 437644
Most possibly the problem is that you have an extra dot in your toggleClass
argument; it should be just toggleClass("newclass")
.
Another possible bug (although it would not prevent your code from doing something) is that you are toggling the class on all the .thisclass
elements if even one of them has the content 0
; I 'm not sure if that's on purpose, so bringing it up.
Finally, you could write the same code in shorter form like this:
// If you want to toggle class on an element-by-element basis
jQuery('.thisclass').filter(function() { return this.innerHTML == " 0 "; })
.toggleClass('.newclass');
// Or if you want to toggle on *all* elements if one matches:
var count = jQuery('.thisclass')
.filter(function() { return this.innerHTML == " 0 "; })
.length;
if(count) {
jQuery('.thisclass').toggleClass('.newclass');
}
Upvotes: 0
Reputation: 48837
This should do the trick:
$(".thisclass").each(function() {
if($(this).html() == "0") {
$(this).removeClass("thisclass");
$(this).addClass("thatclass");
}
});
Upvotes: 3
Reputation: 763
This line is a problem:
jQuery('.thisclass').toggleClass('.newclass');
You need to use the current element here. Also when u do addClass/removeClass/toggleClass u don't need to use dot (".") in class name. Would be something like this.
myElement[i].toggleClass('newclass');
Upvotes: 0
Reputation: 2223
Perhaps removing the spaces around the zero would help?
myElement[i].innerHTML == '0'
Also, try this code instead and see if the alert box is what you're expecting:
var myElement = jQuery('.thisclass');
for(var i=0; i<myElement.length; i++){
alert( myElement[i].innerHTML );
if(myElement[i].innerHTML == ' 0 '){
alert( "Toggling" );
jQuery('.thisclass').toggleClass('.newclass');
alert( "Toggled" );
}
}
The first box will show you what the innerHTML is. The second will show you that the conditional is working. And the third will show you if the jQuery worked.
Upvotes: 1