Search code examples
javascriptjqueryhtmlis-empty

What does an empty div mean in Jquery or Javascript


I have the following empty div inside my html page:

<div id='onlineaccess' style='width:20em;'>
</div>

I need to dynamically update this div with html, but before I do, I need to see if it is empty or not. I have written the following JQuery and Javascript code for this:

if($('#onlineaccess').is(':empty') ) 
{alert('No HTML inside of onlineaccess div');}
else
{alert('Some HTML inside of onlineaccess div');}

but this does not yield the result I am looking for if the div is empty.

if($('#onlineaccess').is(':empty') ) 
{alert('No HTML inside of onlineaccess div');}
else
{alert('Some HTML inside of onlineaccess div');}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='onlineaccess' style='width:20em;'>
    </div>

This alerts the second message even if the div is empty. Can anyone explain to me why is it so and how can I get the first message into the alert?

Thanks in advance for help.


Solution

  • https://api.jquery.com/empty-selector/

    if($('#onlineaccess:empty') ) 
    {alert('No HTML inside of onlineaccess div');}
    else
    {alert('Some HTML inside of onlineaccess div');}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id='onlineaccess' style='width:20em;'>
        </div>