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
  • 10

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,585
  • 1
  • 17
  • 27
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
  • 4,700
  • 2
  • 11
  • 20
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
  • 124,973
  • 10
  • 73
  • 87
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,195
  • 1
  • 9
  • 22