padolsey / findAndReplaceDOMText

:mag: Find and replace DOM text
777 stars 146 forks source link

Allow custom replace functions to return DocumentFragment nodes #86

Open hftf opened 4 years ago

hftf commented 4 years ago

Fixes a bug demonstrated in https://jsfiddle.net/vy3tsq8o/. Code repeated below:

<p id="ex1">11 22</p>
<p id="ex2">11 22</p>
var pattern = /\d+/g;
var replaceFunction = (useDocumentFragment) => function(portion, match) {
  var fragment = (useDocumentFragment) ?
    document.createDocumentFragment() :
    document.createElement('fragment');
  var mark = document.createElement('mark');

  mark.appendChild(document.createTextNode(portion.text))
  fragment.appendChild(document.createTextNode('x'));
  fragment.appendChild(mark);
  fragment.appendChild(document.createTextNode('y'));
  return fragment;
}

findAndReplaceDOMText(ex1, { find: pattern, replace: replaceFunction(false) });
findAndReplaceDOMText(ex2, { find: pattern, replace: replaceFunction(true)  });
hftf commented 3 years ago

Hope you're doing better. Are you still interested in maintaining the project?