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
x
4
1
if($(".parent-class .div-with-certain-class")){
2
/*Execute function*/
3
}
4
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
1
4
1
if($(".parent-class .div-with-certain-class").length>0){
2
/*Execute function*/
3
}
4
See for yourself here:
JavaScript
1
6
1
// test for length
2
console.log($('#this-is-nowhere').length)
3
console.log($('#i-exist').length)
4
5
// vs:
6
console.log($('#this-is-nowhere'))
JavaScript
1
2
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div id='i-exist'></div>