Reputation:
Let say
<div id = "test_id" class = "test_class"> </div>
JS
alert( $("#test_id").hasClass('test_class') ); // result is true
I just write another way to get the same expected result but didn't work, Why?
var test = ' " ' + "test_id" + ' " ' ;
alert( $(test).hasClass('test_class') ); // not working, why ?????
Upvotes: 2
Views: 2183
Reputation: 165971
Firstly, you can't assign a variable like that. The var
is a keyword which signifies a variable declaration is about to occur. Get rid of the first =
sign.
Secondly, you have included the "
characters in your string. Those are used to declare a String literal, which is what you pass into the jQuery function in your first example. They are not part of the string itself.
Third, you didn't include the #
character at the start of the selector in your second example.
If you change your second example to:
var test = '#test_id';
then it should work just fine.
Upvotes: 3
Reputation: 1170
var = test = ' " ' + "test_id" + ' " ' ; //<-- this is wrong
var test = "#test_id"; // <-- this is ok
you are missing some basic skills. probably a tutorial would be useful to clear some basic things up.
Upvotes: 0
Reputation: 342635
You are double-quoting the ID stored in test
:
var test = ' " ' + "test_id" + ' " ' ; // test == '"test_id"' == broken
Just do var test = "test_id"
, and don't forget to prepend the #
Upvotes: 0
Reputation: 50573
you forgot the #:
var test = '#test_id';
alert( $(test).hasClass('test_class') ); // should be working now
Upvotes: 0
Reputation: 15961
The variable 'test' needs to be in the format of an ID selector - i.e. #test
So it should be:
var test = '#test_id';
alert( $(test).hasClass('test_class') );
Upvotes: 1
Reputation: 45589
How about now?
var test = '#test_id'; // no need for the inner double quotes
alert( $(test).hasClass('test_class') );
Upvotes: 0