DTE :]

Sunday, April 22, 2012

JQuery Highlight Text Plugin

jQuery.fn.highlight = function(str, className) {
    var regex = new RegExp(str, "gi");
    return this.each(function() {
        $(this).contents().filter(function() {
            return this.nodeType == 3 && regex.test(this.nodeValue);
        }).replaceWith(function() {
            return (this.nodeValue || "").replace(regex, function(match) {
                return "<span class=\"" + className + "\">" + match + "</span>";
            });
        });
    });
};

Penggunaan

Seleksi sebuah elemen kemudian terapkan fungsi .highlight("teks", "nama-kelas"):

$('p').highlight("lorem ipsum", "yellow");

Lihat Demo


Sumber: A Web Coding Blog - Highlight Words in Text with jQuery

Labels: , , ,

6 Comments:

Post a Comment



<< Home