HasClass Doesn't Work In My Js Code?
Solution 1:
It 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 2:
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')
.
Post a Comment for "HasClass Doesn't Work In My Js Code?"