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

if($(".parent-class .div-with-certain-class")){
   /*Execute function*/
}

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

if($(".parent-class .div-with-certain-class").length>0){
   /*Execute function*/
}

See for yourself here:

// test for length
console.log($('#this-is-nowhere').length)
console.log($('#i-exist').length)

// vs:
console.log($('#this-is-nowhere'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='i-exist'></div>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement