How do I search the DOM for a certain string in the document's text (say, "cheese") then insert some HTML immediately after that string (say, "< b >is fantastic< /b >").
I have tried the following:
for (var tag in document.innerHTML) {
if (tag.matches(/cheese/) != undefined) {
document.innerHTML.append(<b>is fantastic</b>
}
}
(The above is more of an illustration of what I have tried, not the actual code. I expect the syntax is horribly wrong so please excuse any errors, they are not the problem).
Cheers,
Pete
This is crude and not the way to do it, but;
The way to do this is to traverse the document and search each text node for the desired text. Any way involving
innerHTML
is hopelessly flawed.Here's a function that works in all browsers and recursively traverses the DOM within the specified node and replaces occurrences of a piece of text with nodes copied from the supplied template node
replacementNodeTemplate
:Here's an example use:
If you prefer, you can create a wrapper function to allow you to specify the replacement content as a string of HTML instead:
Example:
I've incorporated this into a jsfiddle example: http://jsfiddle.net/timdown/azZsa/
Works in all browsers except IE I think, need confirmation though.
This supports content in iframes as well.
Note, other examples I have seen, like the one above, are RECURSIVE which is potentially bad in javascript which can end in stack overflows, especially in a browser client which has limited memory for such things. Too much recursion can cause javascript to stop executing.
If you don't believe me, try the examples here yourself...
If anyone would like to contribute, the code is here.
There are native methods for finding text inside a document:
MSIE:textRange.findText()
Others: window.find()
Manipulate the given textRange if something was found.
Those methods should provide much more performance than the traversing of the whole document.
Example:
You can use this with JQuery:
I haven't tested this, but something along these lines should work.
Note that
*
will match all elements, evenhtml
, so you may want to usebody *:contains(...)
instead to make sure only elements that are descendants of the document body are looked at.Sample Solution:
Jquery codes: