Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best approach to search some text in body html

As of now I am using the JavaScript search method to replace some text in body HTML like below..

Suppose my html is

 <body>
      <div> I am in body...</div>
 </body>

Then I am using the below approach

 var body = $(body);
 var text = body.html();
 text = text.replace('I am in body...','Yes');
 body.html(text);

But I could see slow page search in browsers like IE..
Please suggest me to improve this and also please let know if there are any plugins to search and match a string even if it contains any html tags in it.. Like below

 <body>
       <div><span>I </span> am in body...</div>
 </body>

With the current method I cannot match this..
If i use

  $('*:contains("some search text string")'); 

This will match the DIV and BODY as well.. But here I want to search the html text not parent element... Thanks

like image 368
Exception Avatar asked Nov 26 '11 03:11

Exception


People also ask

How do you search for text in HTML?

The <input type="search"> defines a text field for entering a search string. Note: Remember to set a name for the search field, otherwise nothing will be submitted. The most common name for search inputs is q.

What is the HTML tag for text?

The HTML <strong> element defines text with strong importance. The content inside is typically displayed in bold.

How do you emphasize text in HTML?

The <em> HTML element marks text that has stress emphasis. The <em> element can be nested, with each level of nesting indicating a greater degree of emphasis.


1 Answers

You should take a look at :

ranges:(to modify text without overwriting the complete body)

IE: http://msdn.microsoft.com/en-us/library/ms535872%28v=vs.85%29.aspx
Others: https://developer.mozilla.org/en/DOM/range


find()/findText()(to create the ranges)

IE: http://msdn.microsoft.com/en-us/library/ms536422%28v=vs.85%29.aspx
Others: https://developer.mozilla.org/en/DOM/window.find

(Opera doesn't support find or findText)


Regarding to that question a small modification:

<html>
<head>

  <script>
  function fx(a,b)
  {
    if(window.find)
    {
      while(window.find(a))
      {

        var rng=window.getSelection().getRangeAt(0);
        rng.deleteContents();

        rng.insertNode(document.createTextNode(b));

      }
    }
    else if(document.body.createTextRange)
    {
      var rng=document.body.createTextRange();
      while(rng.findText(a))
      {
        rng.pasteHTML(b);
      }
    }
  }
  </script>
</head>
<body onload="fx('I am in body...','Yes')">
<div>Oh <span>I </span>am in body...<i>, wonderful</i></div>
</body>
</html>
like image 190
Dr.Molle Avatar answered Sep 17 '22 14:09

Dr.Molle