padolsey/findAndReplaceDOMText

Elements to be avoided

ethantw opened this issue · 3 comments

Avoiding child elements, such as <style> and <script>, to be replaced inside the target elements is necessary; otherwise, it would simply keep them from executing. For example,

<p id="tester">
    <style scoped>span {  color: red;  }</style>

    <span>Hello,</span>
    people in red.
</p>

<script>
findAndReplaceDOMText(
    /red/g,
    document.getElementById('tester'),
    'em'
);
</script>

Would outputs,

<p id="tester">
    <style scoped>span {  color: <em>red</em>;  }</style>

    <span>Hello,</span>
    people in <em>red</em>.
</p>

Tried editing the function, but just not able to make it right. Hoping this could be solved.

Hi, thanks for reporting. In 0.3.0 you can filter out elements:

findAndReplaceDOMText(/foo/g, myElement, 'span', null, function(el) {
    var name = el.nodeName.toLowerCase();
    return name !== 'style' && name !== 'script';
});

Neat! Although the function and the return value are not that comprehensible, it totally works now.

Thanks for the great repo. :)

The function is used to filter what elements should be processed. The above example will return false on SCRIPT and STYLE elements, meaning that they will not be processed. I tried for an intuitive API, and I thought the concept of 'filtering' would be best. Always open to suggestions :)