tags:

views:

57

answers:

3

This jQuery doesnt appear to be working as I would expect it to:

$('#topic li a').filter(function () {
  if ($(this).text() > 410) {
    $(this).parent('li').addClass('wrap');
  }
});

The jQuery should work out if the text within an <a href=>....</a> is over 410 chars, if it is it should add the class .wrap to the parent li.

Anyone have any ideas what im doing wrong?

+10  A: 

jQuery's text() function returns a normal string.
By writing $(this).text() > 410, you are checking whether the string itself is more than 410, by trying to parse the string as a number.

You need to check the length of the string, like this:

if ($(this).text().length > 410)
SLaks
+3  A: 
$('#topic li a').filter(function () {
  if ($(this).text().length > 410) {
    $(this).parent('li').addClass('wrap');
  }
});

When you do $(this).text() > 410 it tries to convert the text to an integer to compare, it most likely is converting the long string to a number like 0. Use .length to get the length of the string returned

Bob Fincheimer
+2  A: 

SLaks' answer is good already but I'm confused with your code.

Maybe you want to write it this way,

$('#topic li a').filter(function(){
   return $(this).text().length > 410;
}).parent('li').addClass('wrap');

or use .each(),

$('#topic li a').each(function(){
  if ($(this).text().length > 410) {
    $(this).parent('li').addClass('wrap');
  }
});
Reigel