开发者

How to find particular class exists on a page using JQuery

I want to write JQuery which will find whether Class="Mandatory" exists on the page and if any element is having this class then only开发者_Go百科 perform certain action.

Thanks


Just check how many elements you hit, when you search for it with jQuery

if ($(".Mandatory").length > 0) {
    // Do stuff with $(".Mandatory")
    $(".Mandatory").each(function() {
        // "this" points to current item in looping through all elements with
        // class="Mandatory"
        $(this).doSomejQueryWithElement();
    }); 
}

EDIT If you wanna do that check for your submit button click, just do that check after the click:

$("input[type='submit']").click(function() {
    if ($(".Mandatory").length > 0) {
        // Do some code here
    }
});


If you want to only do the action once, you could use:

if ($('.Mandatory').length > 0) {
  //do your thing
}

Otherwise if you want to do it for each Mandatory element:

$('.Mandatory').each(function(){
  //do your thing
});


The best way to do this is search class within the body tag.

$('body').find('.Mandatory').length;


Basic jQuery (CSS) selector by class.

if($(".Mandatory").length)


I'd go about it like so:

$('*').hasClass('mandatory') ? "what to do if true" : "what to do if false"

I find ternary conditions more useful as you can set variables more quickly


using hasClass() you can find

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜