07 June 2017

Highlighting text parts



Ever used <Ctrl> + <F> to find something in your page? Why do you use it? Because you want to highlight your search. A small JS can do the trick as well.




function highlight() {
        // containers to search in
        var searchInto = $("div, p, td, h1, h2, h3, h4");
        var args = arguments;
        $(searchInto).each(function () {
            // mark the items only if there is no additional html in it
            // it could destroy the layout otherwise

            if ($(this).html() == $(this).text()) {
                for (var i = 0; i < args.length; i++) {
                    var oldValue = $(this).html();
                    // making the searchstring red
                    var newValue = "<span style=\"color: red;\">" + args[i] + "</span>";
                    // replacing all
                    $(this).html(oldValue.replace(args[i], newValue, "g"));

// call it, with as many searchstring as you wish
highlight("poop", "view", "dog");

No comments:

Post a Comment