MMKY MMKY - 5 months ago 33
jQuery Question

How to check if an element is empty using jquery?

I want to call a function only if HTML of a

td
is empty (like
td
with
contenteditable='true'
), using jQuery.
Note that you should not consider line breaks and spaces.
How can i do something only if

<table>
<tbody>
<tr>
<td contenteditable="true">
<br type="_moz"></br>
</td>
<td contenteditable="false">2</td>
<td contenteditable="false">3</td>
</tr>
<tr>
<td contenteditable="false">4</td>
<td contenteditable="true">
<br type="_moz"></br>
</td>
<td contenteditable="true">
<br type="_moz"></br>
</td>
</tr>
</tbody>
</table>





None of the belows works :

if ($('#element').is(':empty')){
//do something
}


or

if($.trim($("selector").html())=='')

Answer

Use filter() method

$('td').filter(function() {
  return $.trim($(this).text()).length == 0;
})

$('td').filter(function() {
  return $.trim($(this).text()).length == 0;
}).css('border', '1px solid red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td contenteditable="true">
        <br type="_moz">
      </td>
      <td contenteditable="false">2</td>
      <td contenteditable="false">3</td>
    </tr>
    <tr>
      <td contenteditable="false">4</td>
      <td contenteditable="true">
        <br type="_moz">
      </td>
      <td contenteditable="true">
        <br type="_moz">
      </td>
    </tr>
  </tbody>
</table>

Comments