How to find particular class exists on a page using JQuery
Asked Answered
Y

7

29

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 perform certain action.

Thanks

Youngstown answered 12/9, 2011 at 11:29 Comment(0)
A
54

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
    }
});
Abdu answered 12/9, 2011 at 11:30 Comment(2)
Thanks for your reply!!, this mandatory class is being added dynamically on the submit button click, now I don't want to call until any of my element is having is class on it. Please suggestYoungstown
You want to check only after you know the answer? I guess you could keep a flag that gets toggled on by the submit button click.Hornswoggle
B
14

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
});
Bloodless answered 12/9, 2011 at 11:32 Comment(0)
C
10

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

$('body').find('.Mandatory').length;
Chaoan answered 12/9, 2011 at 11:38 Comment(0)
N
6

Basic jQuery (CSS) selector by class.

if($(".Mandatory").length)
Niacin answered 12/9, 2011 at 11:30 Comment(0)
T
4

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

Thereby answered 3/8, 2013 at 21:4 Comment(0)
D
2

using hasClass() you can find

Danforth answered 12/9, 2011 at 11:31 Comment(0)
A
0

One way to find whether a class exists within the body tag.

 if ( $('.mandatory')[0] )
Assuntaassur answered 19/7 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.