Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find particular class exists on a page using JQuery

Tags:

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

Thanks

like image 792
Manoj Singh Avatar asked Sep 12 '11 11:09

Manoj Singh


People also ask

How do you check class is exists in page jQuery?

Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not. This can be used to check for multiple classes.

How do I select a specific class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How can check CSS property value in jQuery?

Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");


2 Answers

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     } }); 
like image 123
peirix Avatar answered Sep 21 '22 00:09

peirix


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 }); 
like image 37
Russell Avatar answered Sep 24 '22 00:09

Russell