最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery hasClass doesn't work for me? - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

5 Answers 5

Reset to default 7

I 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'));
发布评论

评论列表(0)

  1. 暂无评论