I want to use hasClass
in the following code, but that doesn't work for me, please see my demo in jsfiddle and tell me, what do I do wrong?
<span>
<input type="text" name="relation" class="IdRelation">
</span>
if ($('span').hasClass('IdRelation')) {
alert("ok");
}
DEMO
I want to use hasClass
in the following code, but that doesn't work for me, please see my demo in jsfiddle and tell me, what do I do wrong?
<span>
<input type="text" name="relation" class="IdRelation">
</span>
if ($('span').hasClass('IdRelation')) {
alert("ok");
}
DEMO
Share Improve this question edited Jul 26, 2012 at 12:27 mplungjan 179k28 gold badges182 silver badges240 bronze badges asked Jul 26, 2012 at 12:23 jennifer Joliejennifer Jolie 7276 gold badges17 silver badges31 bronze badges 3-
2
It kind of looks like you're using
IdRelation
as a unique marker (obviously just a guess based on your markup). If so you might want to consider usingid="relation"
instead and select it using$("#relation")
. – Vala Commented Jul 26, 2012 at 12:29 -
1
Especially with the prefix
Id
which does not sound like it would be a class – mplungjan Commented Jul 26, 2012 at 12:36 -
1
there is no
span
with a classIdRelation
, did you meaninput
? – jbabey Commented Jul 26, 2012 at 12:39
2 Answers
Reset to default 11It is not the <span>
element that exposes the IdRelation
class, but its <input>
child. Try:
if ($("span input").hasClass("IdRelation")) {
alert("ok");
}
Or maybe, depending on your actual markup:
if ($("span > input").hasClass("IdRelation")) {
alert("ok");
}
The selector in the first code snippet will match all <input>
elements that are descendants of a <span>
element, whereas the selector in the second snippet will match all <input>
elements that are direct children of a <span>
element. Both will match the <input>
element in your sample markup.
Solution
The class is on the <span>
child, an <input>
, so add it in the jQuery selector : $('span input')
.
if ($('span input').hasClass('IdRelation')) {
alert('ok');
}
Try the Demo.
A bit of explanation
Accorting to jQuery documentation, $('span input')
is a descendant selector :
Selects all elements that are descendants of a given ancestor.
You could also use $('span > input')
. It is a child selector :
Selects all direct child elements specified by "child" of elements specified by "parent".
Both are good in your situation, because the input
is a direct child of the <span>
.
If your code was :
<div>
<form>
<input type="text" name="relation" class="IdRelation">
</form>
</div>
The solution will be $('div input')
or $('div > form > input')
.