2

I'm trying to check in jQuery if an element with a certain class contains some text. If it doesn't contain any text, then I want to remove the class.

<div class="description">


</div>
TylerH
  • 20,799
  • 66
  • 75
  • 101
Jeevan
  • 756
  • 13
  • 39

4 Answers4

3

Use :empty

$('.description:empty').removeClass('description');

According to documentation

Select all elements that have no children (including text nodes).

console.log($('.description:empty').length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="description"></div>

However, if there is poorly formed HTML as in the question(unnecessary whitespace), you will have to take a more manual approach

if ($(this).children().length == 0 && $(this).text().trim() == '')

$('.description').each(function() {
  if ($(this).children().length == 0 && $(this).text().trim() == '') {
    console.log('entered');
    $(this).removeClass('description');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="description">


</div>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
0
if(!$('.description').text().length)
    $('.description').hide();
hildende
  • 832
  • 1
  • 13
  • 19
0
if ($('.description').text().trim()=="") {
    $(this).hide();
else {
    /*non-empty actions */
}
connexo
  • 53,704
  • 14
  • 91
  • 128
0

Try this syntex

if($('.description').innrHTML=='')
{
 $('.description').hide()
}
Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32
  • jQuery objects don't have an `.innerHTML` property. Also, the example shown in the question has some whitespace in the element. – nnnnnn Jun 27 '15 at 05:52