1

please help me with a simple problem in jQuery. I have a load of list items on a page and I need to compare the length of the strings within them. If they are greater than 100 characters then I need to add a class to the 'li' otherwise nothing happens. My code so far:

<ul id="mylist">
     <li>This is a string with more than 100 characters in it. This is a string with more                than 100 characters in it.</li>
   <li>This is a string with less than 100</li>
 </ul>

  var len = $("#mylist li").text().length;
    $( "#mylist li" ).each(function() {
    if (len > 100) {
           $(this).addClass("test");
    }
     });

4 Answers 4

1

Check the length of the text of each li like this

$('#mylist li').each(function () {
    if ($(this).text().length > 100) {
        $(this).addClass("test");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Something like the following should work. Put your length check inside the loop:

$("#mylist li").each(function(e,el) {
    var intLen = $(el).text().length;
    if (intLen > 100) {
           $(this).addClass("test");
    }
});

Comments

0

use:

$( "#mylist li" ).each(function() {
  if ($(this).text().length> 100) {
       $(this).addClass("test");
   }
});

Comments

0
var len = $("#mylist li").text().length;

The above code will make use of entire li's text (ie., Total no. of characters within the mylist li's). Hence it is not working.

So keep it inside the each method to check for individual lis.

$( "#mylist li" ).each(function() {
    if ($(this).text().length > 100) {  //individual li 
           $(this).addClass("test");
    }

1 Comment

They were all correct answers but I accepted Praveens because he told me where my error was. Appreciated all the answers...

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.