jQuery: ricerche full-text con evidenziazione delle stringhe

jQuery: ricerche full-text con evidenziazione delle stringhe

Evidenziare una parola o una stringa nel testo è un'operazione semplice se a jQuery associamo alcuni metodi e proprietà dell'implementazione JavaScript del DOM in modo da velocizzare la ricerca e la sostituzione del testo.

Possiamo definire il seguente plugin:


(function($) {

$.fn.highlightText = function(text, className) {
  function highlight(node) {
    if (node.nodeType == 3) {
      var val = node.nodeValue;
      var pos = val.toLowerCase().indexOf(text);
      if (pos >= 0 && !$(node.parentNode).hasClass(className)) {
        var span = document.createElement("span");
        span.className = className;
        span.appendChild(document.createTextNode(val.substr(pos, text.length)));
        node.parentNode.insertBefore(span, node.parentNode.insertBefore(
          document.createTextNode(val.substr(pos + text.length)),
          node.nextSibling));
        node.nodeValue = val.substr(0, pos);
      }
    }
    else if (!$(node).is("button, select, textarea")) {
      $.each(node.childNodes, function() {
        highlight(this);
      });
    }
  }
  return this.each(function() {
    highlight(this);
  });
};

})(jQuery);

Esempio d'uso:


$('#highlight').click(function() {
    $('p').highlightText('risus', 'highlight');
});

Torna su