Explain Codes LogoExplain Codes Logo

Selecting text in an element (akin to highlighting with your mouse)

javascript
prompt-engineering
best-practices
accessibility
Nikita BarsukovbyNikita Barsukov·Jan 14, 2025
TLDR

Do a lightning-fast highlighting of text from a DOM element by harnessing the power of window.getSelection() along with document.createRange():

function highlightText(element) { // Meet the one and only 'Range' – your text's best friend const range = document.createRange(); // Here's your 'Selection' – the life of the party const selection = window.getSelection(); // Never leaves any text behind. What a pal! range.selectNodeContents(element); // Removes unwanted sidekicks. Talk about a clean-up crew! selection.removeAllRanges(); // Let's get this party started! selection.addRange(range); } // Let's get the spotlight on our star 'targetElement'! highlightText(document.getElementById('targetElement'));

To get this working, all you need to do is swap 'targetElement' with the ID of the desired element. This efficient snippet creates a boundary enclosing the contents of the element, manifesting the visual effect of a mouse-generated highlight.

Putting code into context

Case of non-input elements

Our code above is a hardworker. It doesn't discriminate between input or non-input elements like divs, spans, or paragraphs.

Iframes: a unique canvas

When you're dealing with iframes, ensure you've got the right document. And also, remember, security is key! Keep your operations snug within the same domain.

jQuery version: all too familiar

If jQuery prides itself as your go-to syntax, a plugin is probably your favorite rave. Here's how our function looks in jQuery style:

$.fn.highlightText = function() { return this.each(function() { // 'this' here? Just the text we are familiarizing with the spotlight! const element = this; // Our trusty 'Range' steps in const range = document.createRange(); // Here's our trustworthy 'Selection' joining the party const selection = window.getSelection(); // Let's gather all the text for the bash range.selectNodeContents(element); // Out with the old! selection.removeAllRanges(); // In with the new! selection.addRange(range); }); }; // Our star gets the perfect stage again $('#targetElement').highlightText();

This lets you enjoy jQuery's chained syntax and readability.

Enhancing for broader use cases

Mobile devices: the modern norm

Reflect upon mobile device prevalence and make sure your methods translate well on touch events. Use touchstart and touchend to detect gestures resulting in text highlighting.

Keyboard enthusiasts: they exist

Design for users who are keyboard-dependent. Listen for keydown events and invoke text highlighting once detecting the preferred keyboard shortcut.

Dynamic contents & SPAs: the next-gen web

In Single Page Applications (SPAs) or sites with dynamically loaded contents, consider using a MutationObserver to keep tabs on DOM changes and highlight newly inserted elements.

Accessibility: inclusivity matters

Never forget accessibility. Selections may disrupt the flow for users who depend on screen readers. Make sure they can use your feature and that it's announced correctly by assistive technologies.

Security: always critical

Be cognizant of security implications when dealing with cross-origin iframes or user-generated content. Sanitize user inputs and strictly adhere to the Content Security Policy (CSP) best practices.