×

jQuery Tutorial

jQuery Examples

jQuery Practice

How do I check if an html element is empty using jQuery?

In this tutorial, we'll discuss whether is it possible to check if an HTML element is empty or not using jQuery?
Submitted by Pratishtha Saxena, on July 24, 2022

jQuery :empty Selector

This selector of jQuery returns the result 'true' if the selected element is empty and 'false' if the element is not empty. Generally, the empty selector is used along with is() method for implementation. No selector can be used on its own. It is always paired up with some other method.

Syntax:

$('#id').is(':empty');

Here, the role of is() method is to check the selected element to the appropriate selector used.

This way of checking an empty element is very easy. This empty selector not only returns true if the element is empty but also if the element has no children further.

Let's implement this and understand using an example.

Example:

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <style>
      body{
      text-align: center;
      }
    </style>
  </head>
  <body>
    <div id="box1">
      <b>Div 1:</b>
      <div id="Div_1">Hey guys !!!</div>
      <br>
      <button id="bt_1">Click to Check</button>
      <br><br>
    </div>
    <hr>
    <div id="box2">
      <b>Div 2:</b>
      <div id="Div_2"></div>
      <button id="bt_2">Click to Check</button>
      <br><br>
    </div>
  </body>
</html>

jQuery:

$(document).ready(function(){
    $("#bt_1").click(function(){
        $("#box1").css("background", "yellow");
        if ($('#Div_1').is(':empty')){
          console.log("This div is Empty.");
        }else{
          console.log("This div is not Empty.");
        }
    });
    $("#bt_2").click(function(){
        $("#box2").css("background", "yellow");
        if ($('#Div_2').is(':empty')){
          console.log("This div is Empty.");
        }else{
          console.log("This div is not Empty.");
        }
    });
});

Output:

Example 1: Check if an html element is empty

Example 2: Check if an html element is empty





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.