0

I have the following JQuery http://jsfiddle.net/gg9xnkqq/1/

$(document).ready(function () {
    if( $('.one').hasClass('one') ){
        $('.one').css({ 'color' : '#f00' });
    }
});

and this HTML

<div class="one">dfv</div>
<div class="one">dfv</div>
<div class="one">dfv</div>
<div class="one">dfv</div>
<div class="one">dfv</div>
<div class="one">dfv</div>
<div class="one">dfv</div>
<div class="one">dfv</div>
<span class="one">oiuoiuioou</span>

In the if statement, how can I detect if the type of the element with the class one is not body?

So all elements that are not body and have a certain class, will have their class changed.

gespinha
  • 7,968
  • 16
  • 57
  • 91

3 Answers3

3

Since there is only 1 body you can select the elements as follows $('body .one') that way it'll select all the elements with class one inside the body.

Karamazovi
  • 55
  • 1
  • 9
1

Use jQuery not()

$('.one').not('body').css({ 'color' : '#f00' });

This will

Remove elements from the set of matched elements.

Therefore, there is no need for the if

AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

You could just use not():

$('.one').not('body').css({ 'color' : '#f00' });

Or :not():

$('.one:not("body")').css({ 'color' : '#f00' });

Or filter():

$('.one').filter(':not("body")').css({ 'color' : '#f00' });

Or:

$('.one').filter(function () {
    return $(this).not('body');
}).css({ 'color' : '#f00' });

What you don't need to do is:

if( $('.one').hasClass('one') ){
    $('.one').css({ 'color' : '#f00' });
}

Because if the elements didn't have the class of one they wouldn't have been selected by the selector comprising of the class-name one.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410