How to highlight an entire div based on search

I have a sample jsfiddle here.

You'll see I have several div classes created. I can search the text and get a highlighted answer, but I want to be able to search the value of the div and have that entire div (a square box in this case) highlight or fill up with color.

Here's the javascript I have for isolating the text, but I can't get the above issue to work...

function doSearch(text) {
    if (window.find && window.getSelection) {
        document.designMode = "on";
        var sel = window.getSelection();
        sel.collapse(document.body, 0);

        while (window.find(text)) {
            document.getElementById("button").blur();
            document.execCommand("HiliteColor", false, "yellow");
            sel.collapseToEnd();
        }
        document.designMode = "off";
    } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}

Can this be done more appropriately with jQuery?

Answers:

Answer

I forked your fiddle here. I added one line of CSS (a new class: highlight) and shrunk down the doSearch() function to these two lines of jQuery:

$('#content div').removeClass('highlight');
$('#content div:contains(' + text + ')').addClass('highlight');

It first removes the highlight class from every div inside the content div, then adds the class back to any of those divs that contain the desired text.

Answer

Here is an updated fiddle with jquery: http://jsfiddle.net/2e5HZ/2/

function doSearch(text) {    
    $("#content").find("div").each(function() {
        var div = $(this);
        if (div.html() == text) {
            div.addClass('highlight');
        } else {
            div.removeClass('highlight');
        }
    });
}

What I did was find all the divs inside of content, if the html of that div matched the search, we add the highlight class

.highlight { background: yellow; border: 2px solid red; }

If it is not, we remove the highlight class (the reset)

Answer

Here is a solution with pure JS:

jsFiddle

function doSearch(text) {
    var divs = document.getElementById('content').getElementsByTagName('div');
    var pattern = new RegExp(text);
    for (var i in divs) {
        if (pattern.test(divs[i].innerHTML)) {
            var classes = divs[i].className.split(' ');
            classes.push('highlight');
            divs[i].className = classes.join(' ');
        }
    }
}

And add a CSS class:

.highlight {
    background-color: yellow;
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.