qadenza
qadenza

Reputation: 9293

checking if a div is empty and ignoring white spaces

I need to check if a div is empty and ignore white spaces.
If you type one or more spaces inside the below div and click the button, it logs "empty" instead of "not empty".

$('button').on('click', function(){
let a = $('#wrap').html();
if(a == '' || a.trim() == ''){console.log('empty');}
else{console.log('not empty');}
});
.wrap{
background:gold;
min-height:25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap' contenteditable></div>
<button>CLICK</button>

Upvotes: 0

Views: 712

Answers (2)

Always Helping
Always Helping

Reputation: 14570

You can simply jQuery .text() to check for length of any text in div. This will avoid (not count) spaces.

The way .html() works is that it will count white spaces as well.

Run snippet below.

$('button').on('click', function() {
  let a = $('#wrap').text();
  if (a == '' || a.trim() == '') {
    console.log('empty');
  } else {
    console.log('not empty');
  }
});
.wrap {
  background: gold;
  min-height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap' contenteditable></div>
<button>CLICK</button>

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89159

You should use .text() instead. Also, the first check for an empty string is superfluous. The root cause of this issue is that spaces are represented as &nbsp; in HTML, which you can see if you console.log(a).

$('button').on('click', function() {
  let a = $('#wrap').text();
  if (a.trim() == '') {//or simply, if(!a.trim()){
    console.log('empty');
  } else {
    console.log('not empty');
  }
});
.wrap {
  background: gold;
  min-height: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='wrap' id='wrap' contenteditable></div>
<button>CLICK</button>

Upvotes: 1

Related Questions