padolsey/findAndReplaceDOMText

Best way to implement matches across element borders

uxder opened this issue · 4 comments

uxder commented

I noticed that selection will not work across element borders.

For example:

 <div id=="test">
    <h1>This is a test</h1>
    <p>Grumpy wizards make toxic brew for the evil Queen and Jack.</p>
</div>
 findAndReplaceDOMText(document.getElementById('test'), {
   find: /test Grumpy wizards/,
   wrap: 'em'
  });

Won't work. Are there ways around this?

Your example can't work because you don't allow anything except exactly one space (and thus no tags etc.) in your regex between test and Grumpy.

You should fix your regex (e.g. add the /g modifier), use a string instead of a regex.

uxder commented

hmmm. I tried:

/(test).+(Grumpy wizards)/g

and a few other variations but it doesn't work.

Technically there's a newline character and four spaces between "test" and "Grumpy", and to match newlines you'll need \n (unfortunately in JS RegExp's the dot (/./) does not match newline characters).

This seems to work: https://jsfiddle.net/y0su5b1b/

findAndReplaceDOMText(document.getElementById('test'), {
  find: /test[\s\r\n]+Grumpy wizards/,
  wrap: 'em'
});
uxder commented

Brilliant.

Thanks so much guys :)