padolsey / findAndReplaceDOMText

:mag: Find and replace DOM text
780 stars 145 forks source link

Allow passing data to stencil nodes #79

Closed josiahcoad closed 5 years ago

josiahcoad commented 5 years ago

When I pass a simple stencil node to wrap, I want to be able to pass data to the stencil node.

padolsey commented 5 years ago

What kind of data do you want to pass? Data from the match itself? Have you tried using a custom replace function? (these can return Nodes)

Alternatively, you can hack something together, as long as it provides a outerHTML/nodeType. E.g. if you wanted a prefixed index attached to each match:

var index = 0;

findAndReplaceDOMText(document.querySelector('div'), {
  find: /blah/gi,
  wrap: {
    nodeType: 1,
    outerHTML: {
      toString: function() {
        return '<strong>' + ++index + '...</strong>';
      }
    }
  }
});

Demo: https://jsfiddle.net/g9sywub6/1/

If you need actual match data so you can process it somehow then I definitely suggest using the replace option.

josiahcoad commented 5 years ago

Great! This does it, thanks!