← Back to all snippets
JAVASCRIPT

Programmatically Selecting and Highlighting Text in the DOM

Learn to use the Selection and Range APIs to programmatically select, highlight, or manipulate specific text ranges within any DOM element.

function selectTextRange(element, startOffset, endOffset) {
  const selection = window.getSelection();
  const range = document.createRange();

  range.setStart(element, startOffset);
  range.setEnd(element, endOffset);

  selection.removeAllRanges();
  selection.addRange(range);

  // Optional: Scroll to make the selection visible
  // element.focus(); // Useful if element is editable
  // element.scrollIntoView({ behavior: 'smooth', block: 'center' });
}

// Example Usage:
// Assuming an HTML structure like: <p id="myParagraph">This is some <b>text</b> to select.</p>
const paragraph = document.getElementById('myParagraph');

// For plain text nodes, the offset refers to character index.
// If the element has children (e.g., <b>), offsets become more complex,
// referring to child nodes or text nodes within children.

// Let's find the first text node descendant for a simpler example
let textNode = null;
const walker = document.createTreeWalker(paragraph, NodeFilter.SHOW_TEXT, null, false);
while(walker.nextNode()) {
  if (walker.currentNode.nodeType === Node.TEXT_NODE && walker.currentNode.nodeValue.trim().length > 0) {
    textNode = walker.currentNode;
    break;
  }
}

if (textNode) {
  // Example: Select 'some' from the text node 'This is some '
  selectTextRange(textNode, 8, 12);
  console.log('Text selected:', window.getSelection().toString());
} else {
  console.log('No suitable text node found for selection.');
}

// To select across multiple nodes or complex ranges, range.setStart and range.setEnd
// can take different nodes and offsets.
// E.g., select 'some text' where 'text' is in a <b> tag:
// range.setStart(textNodeFor"some ", 8); // 's' of 'some'
// range.setEnd(bTagTextNode, 4); // end of 'text' inside <b>
How it works: This snippet illustrates how to programmatically control text selection in the browser using the `Selection` and `Range` APIs. The `selectTextRange` function takes an element (or a text node) and start/end offsets to define the desired selection. It first creates a `Range` object, sets its boundaries using `setStart` and `setEnd`, then clears any existing selections and applies the new range using `window.getSelection().addRange()`. This technique is crucial for building rich text editors, implementing custom search and highlight features, or creating interactive content where precise text manipulation is needed.

Need help integrating this into your project?

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

Hire DigitalCodeLabs