Dana A
Dana A

Reputation: 31

How do web browsers implement a text search?

I would like to build an application that contains HTML web control, and enables searching and highlighting multiple phrases in the html area, like it's implemented in web browsers today. The main idea is to make the search ignore the html special tags, and refer only to the real text (the inner html). I know that the solution will include editing the DOM, but I'm not sure how this could be implemented. I searched a lot over the net, and I read also the post of Zavael, but unfortunately I couldn't find any suitable answer. Any answer, example or direction will be appreciated.

Upvotes: 3

Views: 1858

Answers (1)

Chris Harrison
Chris Harrison

Reputation: 5838

If you are referring to an inline search of HTML content within the page: firstly I would say that it probably isn't a good idea. You shouldn't supplant the browser's native functionality. Let users do things the way they are used to. Keep the experience consistent across different websites.

However, if you need this for some niche purpose I don't think it would be that hard.

jQuery could achieve it. Just a very rough start:

//As you type in the search box...
$("#search_box").change(function() {
    //...you search the searchable area (maybe use some regex here)
    $("#search_area").html();
});

EDIT: Questioner asked if I can elaborate on the code.

//As you type in the search box...
$("#search_box").change(function() {
    //This part of the code is called when the contents of the search box changes

    //This is the contents of the searchable area:
    $("#search_area").html();

    //This is the contents of the search box:
    $(this).val();

    //So you could perform a function here, like replacing the occurences of the
    //search text with a span (you could use CSS to highlight the span with a
    //background colour:

    var html_contents = $("#search_area").html();
    var search_tem = $(this).val();

    $("#search_area").html(html_contents.replace(search_term, '<span class="highlight">'+search_term+'</span>'));
});

Please note that in the above example, the Javascript 'replace' function will only replace the first occurence. You need to use a regular expression in the first paramater to replace all. But I don't want to write all the code for you ;)

Upvotes: 1

Related Questions