4

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.

Rabia Rana Khan
  • 202
  • 1
  • 11

5 Answers5

2

It's the line break. Seems some browsers interpret this differently than others.

Write it this way:

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

and you get your intended behaviour.

Related: How do I check if an HTML element is empty using jQuery?

Community
  • 1
  • 1
mwallisch
  • 1,751
  • 2
  • 21
  • 29
2

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>
Rikin
  • 5,351
  • 2
  • 15
  • 22
1

var check = !$.trim( $('#div').html() ).length;

if (check) {
  console.log('no html');
} else {
  console.log('some html');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


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

You should get the html() content of your id so should be

  if($.trim($('#onlineaccess').html()) ==='' ) 
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
0

The div is actually not empty, it has a text node inside which counts as non-empty contents. Use this insead:

$(document).ready(function () {
  if ($("#onlineaccess").html() === "") {
    console.log('empty');
  } else {
    console.log('not empty');
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='onlineaccess' style='width:20em;'>
</div>
jetpackpony
  • 1,270
  • 1
  • 12
  • 22