1

How to make this correct?

if( $(this) == $(".className") ){
   alert("Yes!");
}

and the NOT...

if( $(this) != $(".className") ){
   alert("Yes!");
}

Thank you

Ryan
  • 1,783
  • 8
  • 27
  • 42

6 Answers6

5
if($(this).hasClass("className")){
    alert('is class');
}else{
    alert('is not class');
}
Trey
  • 5,480
  • 4
  • 23
  • 30
2

Assuming your $(this) is an element, you can check if it has the class ‘className’:

if ($(this).is('.className')) {
     //$(this) has the class
} else {
     //$(this) doesn't have the class
}
Jules
  • 7,148
  • 6
  • 26
  • 50
2

What your code would do is to compare a jQuery object containing one element with another jQuery object containing all elements with a specific class, so that would supposedly (i.e. if it would have worked) be true if the element has that class, and it's the only element with that class. I don't think that's what you want to do...

If you want to check if the element has a class:

if ($(this).hasClass('className')) {
   alert("Yes!");
}

if (!$(this).hasClass('className')) {
   alert("No!");
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • what if I add a new selection to it and now its an OR and it is still inside the same condition? for example: if ($(this).hasClass('className') || $(this) == $('ul')) ?? – Ryan Jul 07 '11 at 23:28
  • @Eron, then you need to use `is()` as Jules describes in his answer. `$('#foo').is('.className, ul')`. – Alex Wayne Jul 07 '11 at 23:37
  • @Eron: Some things are easier without jQuery: `if ($(this).hasClass('className') || this.tagName == 'UL')`. – Guffa Jul 07 '11 at 23:44
0

You can compare the HTML elements:

$(this).get(0) == $(".className").get(0);
$(this).get(0) != $(".className").get(0); 

Taken from jQuery mailing list:

// Plugin:
(function($){
    jQuery.fn.equals = function(selector) {
        return $(this).get(0)==$(selector).get(0);
    };
})(jQuery); 

// Can be used as:
if (  $(this).equals( $(".className") )) {
   alert('SAME');
} else {
   alert('Not the same');
}
powtac
  • 40,542
  • 28
  • 115
  • 170
0

It is not clear what you want to do but if you want to compare two jQuery objects to determine if they are the same (ie. values, keys, the whole lot) you should use an object comparison function.

Some examples could be found here Object comparison in JavaScript

or you could use underscore.js to perform the comparison

http://documentcloud.github.com/underscore/#isEqual

Community
  • 1
  • 1
Michal
  • 13,439
  • 3
  • 35
  • 33
-1

For the little jQuery I remember the following:

$(".className")

is a selector so returns you a list of objects,

how does it work if your replace it with:

$(".className")[0]

??

Davide Piras
  • 43,984
  • 10
  • 98
  • 147