Highlight API
by WebComponents
HTML
<input value="This is some example text" type="text">
<textarea>
This is some example text
</textarea>
<script>
customElements.define( "my-counter", class extends HTMLElement {
constructor() {
const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props);
super() // sets AND returns 'this' scope
.attachShadow({mode: "open" }) // sets AND returns this.shadowRoot
}
})
const input = document.querySelector('input[type="text"]');
const startIndex = input.value.indexOf("example");
const myOpaqueRange = input.createValueRange(startIndex, startIndex + "example".length);
const greenHighlights = new Highlight(myOpaqueRange);
CSS.highlights.set("green", greenHighlights);
const textarea = document.querySelector('textarea');
const blueHighlights = new Highlight();
CSS.highlights.set("blue", blueHighlights);
function highlightWord() {
blueHighlights.clear();
const matches = textarea.value.matchAll(/\bexample\b/gi);
for (const match of matches) {
blueHighlights.add(textarea.createValueRange(match.index, match.index + "example".length));
}
}
highlightWord();
textarea.addEventListener('input', highlightWord);
</script>