Search code examples
jquerycssjquery-selectorsunrecognized-selectorlivesearch

Jquery change each first .not('class')


I'm trying to make a live search with effect in Jquery and I don't succeed to catch the first word in the text. I wrap each word in a span like that :

<span class="word word-this" id="word-#" aria-hidden="true">this</span>

And for the script I try to add a "readed" class to the word behind the one I search. Every-time I go to the next "this", all "this" words before have the class "readed". Like that :

var word = function(word) {
  $('span').each(function() {
    if ($(this).not('.readed') && $(this).hasClass('word-'+word)){
      // transformation
      $('.word-'+word).first().css('color', 'red').addClass('readed');
    }
  });
};

The problem is that it catch the first occurence of the word but it doesn't find the next, it stay on the first. It doesn't recognize that the "readed" class was added. I don't know if it's a .first() or .not() problem or another thing.


Solution

  • I found two bugs.

    • $('.word-'+word).first() is the first span which has .word-<word>.
    • $(this).not('.readed') is a object so it is always true as a condition of if statement.

    This is working code:

    var word = function(word) {
      $('span').not('.readed').each(function() {
        if ($(this).hasClass('word-'+word)) {
          // transformation
          $(this).css('color', 'red').addClass('readed');
          // interrupt the each loop
          return false;
        }
      });
    };
    

    I found a more simple implementation.

    var word = function(word) {
      $('span.word-'+word).not('.readed').first().each(function() {
        $(this).css('color', 'red').addClass('readed');
      });
    };