DOM Find and Replace Utility
This utility, `heti-findandreplacedomtext`, is a fork of the original `padolsey/findAndReplaceDOMText` library. Its core function is to search for regular expression matches within a given DOM node and subsequently replace or wrap each match with a specified node or piece of text. A key differentiator is its robust handling of matches that span across multiple DOM nodes, ensuring that all fragmented portions of a match are correctly processed and modified. The `heti-` fork specifically introduced an `offset` option to address and fix issues related to browser support for regex lookbehind, enhancing cross-browser compatibility. The package's current stable version, 0.5.0, was published over six years ago, indicating that active development has ceased and the package is largely unmaintained. It is primarily used for client-side DOM manipulation tasks without notable external runtime dependencies. For TypeScript users, community-maintained type definitions (`@types/findandreplacedomtext`) are available.
Common errors
-
TypeError: findAndReplaceDOMText is not a function
cause The `findAndReplaceDOMText` function was not correctly imported or the library script was not loaded into the page. This is common when mixing module types (e.g., trying to `require` a library designed for global script inclusion) or if the `npm install` command did not target the correct package (`heti-findandreplacedomtext`).fixIf using npm/bundlers, ensure `import findAndReplaceDOMText from 'heti-findandreplacedomtext';` is at the top of your file. If using a script tag, verify the `<script>` tag pointing to `findAndReplaceDOMText.js` is correctly placed and loaded before its usage. Also verify the package name in `npm install` and `import` matches `heti-findandreplacedomtext`. -
Only the first occurrence of my search term is being replaced/wrapped.
cause When using a regular expression for the `find` option, the global flag (`/g`) was omitted, causing `RegExp.prototype.exec` to only find the first match.fixModify your `find` regular expression to include the global flag, e.g., change `/myword/` to `/myword/g`. -
The DOM structure appears corrupted or unexpectedly nested after replacement, especially with complex replacements.
cause This can occur if the `replace` function is not carefully constructing new nodes, or if the `portionMode` is not suitable for the desired outcome, leading to incorrect node splitting or merging. It can also happen when the original DOM structure is heavily modified or normalized after the initial replacement, making reversion unpredictable.fixReview your `replace` function to ensure it consistently returns valid DOM nodes or strings. Consider adjusting the `portionMode` option (default is 'retain'). If you need to revert changes, save a clone of the original DOM subtree before modification, as the built-in `revert()` method may fail if the DOM is significantly altered elsewhere.
Warnings
- gotcha When using regular expressions for the `find` option, ensure the global flag (`/g`) is included if you intend to find and replace all occurrences. Without it, only the first match will be processed.
- gotcha The default `portionMode` is 'retain', which re-uses existing node boundaries. If you need the entire replacement to reside within the first-found match portion's node, set `portionMode: 'first'`. Most use cases benefit from the default 'retain' behavior.
- gotcha When using the `replace` option with a function, be cautious about injecting untrusted user-generated content directly into the DOM, as this can lead to Cross-Site Scripting (XSS) vulnerabilities. Always sanitize inputs.
- gotcha Operating on very large or frequently changing DOM trees can lead to performance issues due to extensive DOM traversal and manipulation. Use `filterElements` and `forceContext` to narrow the scope if possible.
- gotcha The package does not ship with TypeScript type definitions directly. While it can be used in TypeScript projects, you'll need to install `@types/findandreplacedomtext` for proper type checking and IDE assistance.
Install
-
npm install heti-findandreplacedomtext -
yarn add heti-findandreplacedomtext -
pnpm add heti-findandreplacedomtext
Imports
- findAndReplaceDOMText
const findAndReplaceDOMText = require('heti-findandreplacedomtext');import findAndReplaceDOMText from 'heti-findandreplacedomtext';
- findAndReplaceDOMText (global)
<!-- In HTML: --><script src="path/to/findAndReplaceDOMText.js"></script> <script> findAndReplaceDOMText(document.body, { find: /foo/, wrap: 'span' }); </script> - findAndReplaceDOMText (TypeScript)
import findAndReplaceDOMText from 'heti-findandreplacedomtext'; // Ensure @types/findandreplacedomtext is installed for type support // npm install --save-dev @types/findandreplacedomtext
Quickstart
document.body.innerHTML = `
<p id="t1">
123 456 Hello
</p>
<p id="t2">
123 456 Hell<span>o Goodbye</span>
</p>
<div id="t3">
This is a test. Another test word.
</div>
`;
import findAndReplaceDOMText from 'heti-findandreplacedomtext';
console.log('Original DOM content:');
console.log(document.body.innerHTML);
// Example 1: Basic wrap
findAndReplaceDOMText(document.getElementById('t1'), {
find: /Hello/,
wrap: 'em'
});
// Example 2: Wrap across multiple nodes
findAndReplaceDOMText(document.getElementById('t2'), {
find: /Hello/,
wrap: 'strong'
});
// Example 3: Replace text using a function
findAndReplaceDOMText(document.getElementById('t3'), {
find: /test/g,
replace: function(portion, match) {
const span = document.createElement('span');
span.style.color = 'blue';
span.textContent = portion.text.toUpperCase();
return span;
}
});
console.log('\nModified DOM content:');
console.log(document.body.innerHTML);