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.

2
  • 1
    :empty: "Select all elements that have no children (including text nodes)" Commented Feb 11, 2017 at 14:19
  • 1
    The div isn't empty. It contains whitespace. Commented Feb 11, 2017 at 14:22

5 Answers 5

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>

Sign up to request clarification or add additional context in comments.

Comments

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?

2 Comments

Instead of marking this question as a duplicate you post the duplicate as part of your answer? O.o
Don't know how to do that.
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>

Comments

0

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

  if($.trim($('#onlineaccess').html()) ==='' ) 

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.