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
Answer
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>