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");
}
Solution
The class is on the
<span>child, an<input>, so add it in the jQuery selector :$('span input').Try the Demo.
A bit of explanation
Accorting to jQuery documentation,
$('span input')is a descendant selector :You could also use
$('span > input'). It is a child selector :Both are good in your situation, because the
inputis a direct child of the<span>.If your code was :
The solution will be
$('div input')or$('div > form > input').