简体   繁体   中英

hasClass doesn't work in my js code?

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

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

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') .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM