0

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())=='')
3

2 Answers 2

2

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>

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

3 Comments

Is this return an array of empty cells ?
@MMKY : jQuery object of empty cells, if you want as array use get() method
I reached my goal using if(emptyObj.length != 0) { // do sth }
0

One more..

$('td').each(function() {
  if(!$(this).text().trim().length){
      $(this).css('border', '1px solid black');
  }
});

$('td').each(function() {
  if(!$(this).text().trim().length){
      $(this).css('border', '1px solid black');
  }
});
    <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>

2 Comments

What's the difference ? is it duplicate answer ?
@MMKY of course i used the legend but modified by mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.