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


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.