
Replacing text in the DOM… solved? - bpierre
http://james.padolsey.com/javascript/replacing-text-in-the-dom-solved/
======
albertoavila
I actually did something like that a few months ago:
<https://gist.github.com/3050333>

Only the problem was a bit different, I wanted to be able to select a section
of a blog post to generate a url fragment representing that selection, so, if
you shared it, that section would be highlighted when entering the page, but
the underlying problem is the same, example:

[http://gnozin.com/sobremesa/2012/07/02/buena_venta/#highligh...](http://gnozin.com/sobremesa/2012/07/02/buena_venta/#highlight:9-1|110,158)

~~~
timdown
Looks similar to the serializer module of my rangy project:

<http://rangy.googlecode.com/svn/trunk/demos/serializer.html>

~~~
albertoavila
Hey!, it's seems pretty similar indeed, obviously your lib seems to have a lot
more of work put into it than my quick hack, seems pretty cool.

------
xutopia
I did something similar as a jQuery plugin here:
<https://github.com/garyharan/jquery-replace-utilities>

~~~
padolsey
This doesn't solve the cross-element-boundary problem though. If a match
starts in one element but ends in another this plugin doesn't seem to replace
it at all.

------
mkmcdonald
Oddly enough, I was working on a similar problem earlier today.

I've found that collecting the Text nodes and returning them in an Array is
preferable. All it requires is some simple traversal. The developer (that
should know what text goes where) can then map text to nodes.

------
macowar
This bookmarklet uses xpath to replace every plain text 'the' with 'ye'.

javascript:d=document;x=d.evaluate(‘.//text()[normalize-
space(.)!=\'\']‘,d.body,null,7,null);for(i=0,l=x.snapshotLength;i<l;i++){t=x.snapshotItem(i);
t.data=t.data.replace(/the/gi,'ye')} void(1)

------
wslh
The thing is that also depends on the browser version. You couldn't do that
for IE 8 and below because there is not real DOMRange support.

~~~
padolsey
I haven't tested it on IE8 tbh, but this solution doesn't actually use native
DOM ranges.

~~~
wslh
If I remember well the issue came when you want to replace text from a
selection.

------
tantalor
Why not make this a method of Element?

    
    
      myElement.findAndReplaceText(/foo/, 'em');

------
jQueryIsAwesome
One of the reasons not to use the innerHTML prop is because (almost) all
interactivity gets broken; for example a CSS3 animation restarts if you set
innerHTML of one of its parent elements.

Another reason is because IE (even the 9) likes to delete white-spaces when
you set innerHTML; even in PRE tags!

