jQuery Selector Exists Examples
Did you ever come across a requirement where you needed to check if selector exists in jQuery? In this article, I am going to share with you different ways to check if selector exists or not using jQuery with examples.
How to use jQuery to Check if Selector Exists Or Not – Examples
We can find out whether a selector exists or not in jQuery using the .length property. I am using the following HTML source code for the examples. The examples assume that there is already a div with ID “my_div” and we are checking to see if it exists along with a check for a non-existent div with ID “my_div1”.
Common HTML source code for all following examples:
<html> <head> <title>Check if Selector Exists or Not</title> <script type="text/javascript" src="js/jquery_1.7.1_min.js"></script> </head> <body> <div id="my_div" class="my_class">Some content in the div.</div> <button id="check">Check</button> </body> </html>
Example 1: Check if Selector Exists in jQuery using length
<script type="text/javascript">
$(document).ready(function() {
$("#check").click( function() {
//A simple way to check for the length of the selector
if( $("#my_div").length )
{
alert('Yes');
}
//A negation used in conjunction with the length property to check for existence of the selector
if( !$("#my_div1").length )
{
alert('No');
}
});
});
</script>Example 2: Check if Selector Exists in jQuery using length (alternate)
<script type="text/javascript">
$(document).ready(function() {
$("#check").click( function() {
//If the length is more than 0, then the selector exists
if( $("#my_div").length > 0 )
{
alert('Yes');
}
//If the length is 0, then the selector does not exist
if( $("#my_div1").length == 0 )
{
alert('No');
}
});
});
</script>You can use any of the above ways to check if a selector exist or not in jQuery.
Your Turn!
Do you know of any other ways to use jQuery to check if selector exists or not? Share your thoughts with us.
how you will do it in PHP?
Pman
May 16, 2013 at 3:36 pm
You can do this using DOMDocument. But for this, you will need to load at least the part the contains the selector, in PHP. Consider following example: