AJDEV
AJDEV

Reputation: 5760

Filter through elements and only select elements with text

<div id="page-content">
  <ul>
   <li>Text</li>
   <li>Text 2 </li>
  </ul
  <div class="heading">
    <h2>Heading</h2>
  </div>
</div>

I got the above HTML code as an example. I want to filter through each of the elements and only add a class to elements with text. I got some jQuery below:

$(document).ready(function(){
  $('#page-content').find('*').each(function(){
    if ($(this).text().trim().length){
      $(this).addClass('yay');
    }
  });
});

The code find each item in the page-content element and checks if it has text and add the class 'yay'. This does work, however it will give the parent element the class if its child has text in it. eg. It will give the <ul> the class because the <li> has text.

Is there something wrong with the code I am using or do I need to use a completely different script to only apply a class to elements with text?

NOTE The HTML is generated so I might end up with a <ol> instead of a <ul>, or a <a> tag contained inside #page-content.

Upvotes: 2

Views: 117

Answers (1)

Hector Barbossa
Hector Barbossa

Reputation: 5528

You can modify the code to check if the element has any children, and add the class only if this is a text node. But if the HTML is not well formed this might cause problems.

$(document).ready(function() {
      $('#page-content').find('*').each(function() {
          if ($(this).children().length == 0 && $(this).text().trim().length) {
              $(this).addClass('yay');
          }
      });
  });

Upvotes: 1

Related Questions