Reputation: 1309
I am facing a problem while accessing the class of an input tag. First i was using following line of code and it was returning me false.
$('#metaField_932.value').hasClass('hasDatepicker')
then i used following line of code and it returned me true
$("input[id='metaField_932.value']").hasClass('hasDatepicker')
Can anyone explain why this is happening .
Note:There is no id duplication in the code.
Upvotes: 2
Views: 510
Reputation: 886
The selector #metaField_932.value
searches for element with id metaField_932
and class value
. You need to escape the .
character as given in answers by others.
Upvotes: 1
Reputation: 9174
First lets analyze the selector that you passed to jquery in the first code
#metaField_932.value
If you take a close look at it, it means select the element with id as metaField_932
and class as value
. As no such element exists the first code does not return anything
Now for the second piece of code works because its an attribute selector and it does not has such confusion.
As F0G has already explain, you will have to escape the .
with \\
so jQuery can interpret the entire selector as an id
Therefore $("#metaField_932\\.value").hasClass('hasDatepicker')
shall work
Upvotes: 0
Reputation: 11610
Your first line is looking for an HTML element that looks like this:
<input id="metaField_392" class="value">
whereas the second one is looking for one that looks more like your actual HTML element:
<input id="metaField_392.value">
Any selector with a .
in it indicates that it is to search for an element with a particular class
.
To work around this, I'd advise either just using the second selector, or simply removing the period from the element's id
, since that makes it rather unclear.
Upvotes: 4
Reputation: 40639
Escape .
by \
because you are searching for id
not class
and selector
preceeded by a .
searches for a class
like,
$("input[id='metaField_932\.value']").hasClass('hasDatepicker')
Or
$('#metaField_932\\.value').hasClass('hasDatepicker')
Upvotes: 1
Reputation: 2587
try
$("#metaField_932\\.value").hasClass('hasDatepicker')
It's because #metaField_932.value
is selecting element with id metaField_932
and with class value
. You have to escape dot character.
Upvotes: 4