Skip to main content

Check If Class Exists On Page With jQuery

By April 13, 2016Blog, Javascript, jQuery
Allure Web Solutions Code Snippet
if ($(".class")[0]) {
    // do something here
}

Basically what is happening is the class selector is being targeted and put into an index. If there is one or more instances of the class class then that if statement evaluates as true and the code inside is executed.

The alternative would be to check if the $('.class') array has a length of greater than 0:

if ($('.class').length > 0) { // do something }

CodePen Example

If you want to play around with it, change the class name from test to something else in the HTML and click rerun. The h1 will say that the class doesn’t exist if the class name is something other than test.

See the Pen Check If Class Exists On Page With jQuery by Mike Doubintchik (@allurewebsolutions) on CodePen.

allure

Author allure

More posts by allure

Join the discussion 2 Comments

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017