This code snippet helps you to highlight specific text range in HTML using JavaScript and CSS. It adds color to selected text portions. It helps emphasize or categorize content visually.
How to Create Highlight Text To Specific Range In JavaScript
1. First, you need an HTML element containing the text you want to highlight. For example:
<pre><code>this is my highlighted code</code></pre>
2. Create a CSS file named styles.css
and define the styles for highlighting: In the CSS, we define two highlight styles: rangeA
for red and rangeB
for yellow.
html { font-size: 5vmin; text-align: center; } ::highlight(rangeA) { background-color: rgb(255 0 0 / 0.5) /* red */ } ::highlight(rangeB) { background-color: rgb(255 255 0 / 0.5) /* yellow */ }
3. Now, let’s add JavaScript to highlight the desired text ranges. It selects the text node within the code
element and defines two highlight ranges (rangeA
and rangeB
), then applies them using CSS.
console.clear() let text_node = document.querySelector(&singleQuote;code&singleQuote;).firstChild let highlightA = new Highlight() let rangeA = new Range() rangeA.setStart(text_node, 0) rangeA.setEnd(text_node, 15) highlightA.add(rangeA) CSS.highlights.set(&singleQuote;rangeA&singleQuote;, highlightA) let highlightB = new Highlight() let rangeB = new Range() rangeB.setStart(text_node, 10) rangeB.setEnd(text_node, 25) highlightB.add(rangeB) CSS.highlights.set(&singleQuote;rangeB&singleQuote;, highlightB)
You can easily customize the highlight colors by adjusting the RGBA values in your CSS code. Modify the background-color property within the ::highlight pseudo-elements to achieve the desired color effect. Experiment with different RGBA combinations to find the colors that best complement your website’s design.
To highlight different text ranges, simply adjust the start and end positions of the ranges in your JavaScript code. Use the setStart() and setEnd() methods of the Range object to specify the beginning and ending points of each range.
That’s all! hopefully, You’ve successfully implemented text highlighting to specific ranges using JavaScript and CSS. Feel free to experiment with different ranges and styles to suit your needs.
Similar Code Snippets:
I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.