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 this, I need to see if it is empty or not. I wrote 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 give the result I'm 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>
Run codeHide result

This is a warning about the second message, even if the div is empty. Can someone explain to me why this is so, and how can I get the first message in an alert?

Thanks in advance for your help.

+4
source share
5 answers

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>
Run codeHide result
+2
source

. , , .

:

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

.

: , HTML jQuery?

+2

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>
Run codeHide result
+1
source

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

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

The div is actually not empty, it has the text node inside, which is considered non-empty content. 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>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1669460/


All Articles