← Back to all snippets
JAVASCRIPT

Programmatic Text Selection and Range Manipulation

Learn to programmatically select specific text, create custom ranges, and highlight content within the DOM using JavaScript's Selection and Range APIs for enhanced user interaction.

// Assume an element with some text
// <p id="targetText">This is some example text to demonstrate selection.</p>

const targetElement = document.getElementById('targetText');

if (targetElement) {
    // 1. Get the current user selection
    const selection = window.getSelection();
    console.log('Current user selection:', selection.toString());

    // 2. Programmatically select a specific part of the text
    const range = document.createRange();
    range.selectNodeContents(targetElement); // Select all text in the element
    // Or to select a specific portion:
    // range.setStart(targetElement.firstChild, 8); // Start after "is some "
    // range.setEnd(targetElement.firstChild, 15); // End before " example"

    selection.removeAllRanges(); // Clear any existing selection
    selection.addRange(range); // Add the new range to the selection

    console.log('Programmatically selected text:', selection.toString());

    // 3. Highlight the selected text (requires CSS)
    // You'd typically wrap the selected text in a <span> with a highlight class
    // Example (conceptual, actual implementation can be complex for arbitrary ranges):
    // const selectedTextNode = range.extractContents();
    // const span = document.createElement('span');
    // span.style.backgroundColor = 'yellow';
    // span.appendChild(selectedTextNode);
    // range.insertNode(span);

} else {
    console.error('Target element #targetText not found.');
}
How it works: The `window.getSelection()` method returns a `Selection` object representing the user's current text selection. The `document.createRange()` method creates a new `Range` object, which defines a start and end point within the DOM. By combining these, you can programmatically select text (e.g., `range.selectNodeContents()` or `range.setStart()/setEnd()`) and then apply that range to the selection using `selection.addRange()`. This is invaluable for features like text highlighting, rich text editors, or dynamic content annotation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs