This doesn't seem to work - count the length of the text

This jQuery does not seem to work as I would expect this:

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

jQuery should work if the text <a href=>....</a>exceeds 410 characters, if it should add the .wrap class to the parent li.

Anyone have any ideas what I'm doing wrong?

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

When you execute $(this).text() > 410, it tries to convert the text to an integer for comparison, it most likely converts a long string to a number, for example 0. Use .lengthto get the length of the returned string

+4
source

jQuery text() .
$(this).text() > 410, , 410, .

, :

if ($(this).text().length > 410)
+10

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

Perhaps you want to write it in such a 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');
  }
});
+2
source

Source: https://habr.com/ru/post/1759168/


All Articles