admin管理员组文章数量:1325756
In following code, hasClass
doesn't work and result is false
in alert. why, what do i do?
Online Demo: /
HTML:
<span>
<div class="adding"></div>
</span>
JS:
alert($('span').hasClass('adding'));
In following code, hasClass
doesn't work and result is false
in alert. why, what do i do?
Online Demo: http://jsfiddle/Fe3CK/
HTML:
<span>
<div class="adding"></div>
</span>
JS:
alert($('span').hasClass('adding'));
Share
Improve this question
asked Feb 18, 2014 at 6:23
kim singhkim singh
871 silver badge7 bronze badges
2
-
4
You shouldn't put a
<div>
inside a<span>
. – Ja͢ck Commented Feb 18, 2014 at 6:25 - 1 you are checking the span for this class , but actually div has it ..so output false is correct – Dimag Kharab Commented Feb 18, 2014 at 6:25
5 Answers
Reset to default 7I think you might be misunderstanding what .hasClass
does. It checks whether the element itself has one of these classes assigned. From the documentation:
Determine whether any of the matched elements are assigned the given class.
If you want to check whether the element contains an element with that class, use .has
:
Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.
alert($('span').has('.adding').length > 0);
You need:
alert($('span div').hasClass('adding'));
since your span
does not have any class adding
. Only the child div of your span has it.
Updated Fiddle
Note: Only inline elements may be contained within inline elements. span is an inline element so block level elements like div or p cannot appear within a span.
Hence, <div>
inside <span>
tag is not a valid HTML5 markup so you should use <div>
instead of <span>
in this case.
You have to select div not span , as div has class of 'adding'
alert($('div').hasClass('adding'));
Demo
If you want to check any children of span has class, then you can try like this;
alert($('span').children().hasClass('adding'));
div inside a span is not a good practice and your span not have any class adding , adding is its child object's class so please use like
alert($('span').children().hasClass('adding'));
本文标签: javascriptjQuery hasClass doesn39t work for meStack Overflow
版权声明:本文标题:javascript - jQuery hasClass doesn't work for me? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742191282a2430261.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论