jQuery

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.

2 Comments on jQuery Selector Exists Examples

  1. 1

    how you will do it in PHP?

    • 2

      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:

      ';
      $dom = new DOMDocument;
      $dom->loadHTML($html);

      $element1 = $dom->getElementById('my_div');
      // The value of the dump will be null if tehs element is not found
      var_dump($element1); //This will output: object(DOMElement)[2]

      $element2 = $dom->getElementById('my_div2');
      // The value of the dump will be null if tehs element is not found
      var_dump($element2); //This will output: null
      ?>

Leave a Reply to Pman Cancel reply

*

*