Skip to content
Advertisement

Search in current page using jQuery

I have a code in jQuery that searches if a div tag exists with a certain class, a function should be executed.

The code works fine, but the issue is that the function is executed in every page because the div exists on the website.

Is there a way to check if the div exists on the current page or not.

This is my code

JavaScript

I want the function to execute only if the div-with-certain class exists on the current page. Is it possible using jQuery.

Advertisement

Answer

You need to test for length – in jQuery you can search for $('#this-id-does-not-exist') and you’ll get a truthy response, but the length property will be 0

JavaScript

See for yourself here:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement