jQuery Selector How to - Select all elements that have no children (including text nodes)








Question

We would like to know how to select all elements that have no children (including text nodes).

Answer


<!--from w  ww  .j a v a  2 s . co  m-->
<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
    $(document).ready(function(){
         $("td:empty").text("Was empty").css('background', 'rgb(255,220,200)');
    });
    </script>
  </head>
  <body>
      <table>
          <tr><td>data</td><td></td></tr>
          <tr><td>data</td><td></td></tr>
          <tr><td>data</td><td></td></tr>
      </table>
  </body>
</html>

The code above is rendered as follows: