0

I am using jQuery and creating now search. And i want to change all words that match of search.

For example:

i type in textbox "hello world", Script get all words "hello" and "world" on page and replace it on "<b class="search_word">hello</b>" and "<b class="search_word">word</b>".

Is it possible?

PS.

Search in div but div contains many other html elements.

now i am using this:

if ($("#search_input").val() != "") {
    var words = $("#search_input").val().split(/\s/g)
    for (var i = 0; i < words.length; i++) {
        var new_reg = new RegExp(words[i], 'gi');
        var replaced = $(".content_area").html().replace(new_reg, "<b class='searched_word'>"+words[i]+"</b>")
        $(".content_area").html(replaced);
    }
}

it works but tags...

if i search something like: "b class is the best class in School" it destroy page structure

Mirgorod
  • 31,413
  • 18
  • 51
  • 63
  • You say "on page", do you mean in a single DIV or P element, or do really mean "anywhere in the whole of the HTML on the page? The first is easy, the latter more difficult. A listing of the relevant HTML would be useful for people to answer this. – Neil Feb 05 '11 at 14:51

1 Answers1

2

Ahh ok, I understand, "onpage" search... hm....

this is a copy from How do I select text nodes with jQuery?

var getTextNodesIn = (function() {
    function textNodeFilter() {
        return this.nodeType == 3;
    }

    return function(el) {
        var $el = $(el);
        return $el
            .contents()
            .filter(textNodeFilter)
            .add(
                $el
                   .find("*")
                   .contents()
                   .filter(textNodeFilter)
            );
    };
})();

you can now use

getTextNodesIn("body").each(function() {
 var txt = $(this).text();
 $(this).text(txt.replace(new RegExp(myWord,"g"), "<b>" + myWord + "</b>"));
});

Loop now through all of them and aply my filter previously written.

There where you found your word, you must select the whole text, and replace the found word with found Word

Community
  • 1
  • 1
Luke
  • 8,235
  • 3
  • 22
  • 36
  • Aham, look at this var replaced = $(".content_area").html().replace(/Наверняка/, "!!!") $(".content_area").html(replaced); How can i update this to replace not only first word but every words? – Mirgorod Feb 05 '11 at 15:00
  • see my update please. Please do not use "html" since it will search html too, and don´t replace the whole contentarea with your new html,because you might destroy event binding. Always only text and always only replace by it´s parent container – Luke Feb 05 '11 at 15:12
  • something wrong in this $(this).text(txt.replace(new RegExp(myWord,"g"), "" + myWord + "")); line – Mirgorod Feb 05 '11 at 19:01
  • As I said above, and so has Luke, without a listing of the relevant HTML it is difficult to help you! – Neil Feb 06 '11 at 15:17