Skip to content

jQuery check if element exists

  • by

To check if an element exists using jQuery, you can use the length property. The length property returns the number of elements that match a given selector. The length will be greater than zero if the element exists, and zero if the element does not exist.

The if statement in the code snippets you provided are two common ways to check if an element exists using jQuery, based on whether the selector is using an id or a class.

If you are using an id selector to check if an element exists, you can use the # symbol before the id name, like this:

if ($('#selector').length) {
    // it exists
}

If you are using a class selector to check if an element exists, you can use the . symbol before the class name, like this:

if ($('.selector').length) {
    // it exists
}

In both cases, the length property is used to check if the element exists.

jQuery checks if the element exists example

Simple example code.

<!DOCTYPE html>
<html>
<head>
  <title>Example Page</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      // check if element with ID 'my-element' exists
      if ($('#my-element').length) {

        // element exists, change its text
        $('#my-element').text('Element exists!');

      } else {

        // element doesn't exist, create it
        $('body').append('<div id="my-element">New Element</div>');
        
      }
    });
  </script>
</head>
<body>
</body>
</html>

Output:

jQuery check if element exists

If the element does not exist, a new <div> element with the ID my-element is created using the append() method and added to the <body> section of the HTML file.

Another example uses jQuery to check if an element exists:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      if ($('#myElement').length) {
        console.log('The element exists');
      } else {
        console.log('The element does not exist');
      }
    });
  </script>
</head>
<body>

  <div id="myElement">Hello, World!</div>

</body>
</html>

Do comment if you have any doubts or suggestions on this HTML element topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading