window.getSelection() in JavaScript: how to detect selected text, highlight it, and create notes

- Andrés Cruz - ES En español

Video thumbnail

Today I'm sharing something I think you'll find very useful: when a user selects text on your page, you can offer them options like highlighting it or adding a custom note. To achieve this, JavaScript provides us with the function:

window.getSelection();

What window.getSelection() is and how it works

If you've ever wanted to know exactly what text a user is selecting on your page, window.getSelection() is your best ally. This function returns a Selection object representing the range of selected text, or the current position of the cursor (caret) within the document when nothing is selected.

The Selection object you get includes the following key properties:

  • anchorNode and focusNode: the start and end nodes of the selection, respectively.
  • anchorOffset and focusOffset: the exact positions (in number of characters) within those nodes.
  • isCollapsed: a boolean indicating whether the selection is empty (the cursor is positioned but no text is selected).
  • rangeCount: the number of ranges contained in the selection (usually 1).

Note: document.getSelection() works in a practically identical way and in many cases you can use it as a synonym. The difference is subtle: document.getSelection() always refers to the current document, whereas window.getSelection() can operate in broader window contexts, such as iframes.

How to get the selected text in JavaScript

To test the method in action, the most basic usage is this:

const selectedText = window.getSelection().toString();
console.log(selectedText);

Open your browser's developer console, select any text on the webpage, and then run that line of code. You will see an output similar to the following, where the complete Selection object is dumped with all its properties:

Selection {anchorNode: text, anchorOffset: 9, focusNode: text, focusOffset: 47, isCollapsed: false, …}
anchorNode
: 
text
anchorOffset
: 
9
baseNode
: 
text
baseOffset
: 
9
extentNode
: 
text
extentOffset
: 
47
focusNode
: 
text
focusOffset
: 
47
isCollapsed
: 
false
rangeCount
: 
1
type
: 
"Range"

The big problem with window.getSelection(): the cursed range

This is where the ordeal begins. The main problem appears when the paragraph is not clean, but contains <span> elements or other internal nodes, as happens when you have already applied some previous highlighting. Compare these two scenarios:

Clean paragraph (ideal case):

<p id="p_1739646025565_337622">Laravel, al igual que otros frameworks, puede&nbsp;ejecutarse en diversos entornos tanto en ambiente de producción como de desarrollo:</p>

Paragraph with internal spans (the real problem):

<p id="p_1739646025565_337622">Laravel, al igua<span title="Test" id="_p_1739646025565_337622" class="bg-purple-700 rounded-sm no-set-note text-white">l que otros frame</span>works, <span id="span_1739646025565_102820">puede&nbsp;ejecutarse en diversos entornos tanto en ambiente de producción como de desarrollo:</span></p>

If the user selects the text "iversos entornos tanto en ambien", that is, the fragment right next to the <span>, the range returned by window.getSelection() will be generated starting from that <span> and not from the root paragraph. This means any position calculation (to draw a bubble, for example) will be anchored to the <span>, not the <p>, which breaks any logic depending on offsets relative to the main container. It's not a bug: it's the expected DOM behavior, but it is an endless source of headaches.

Common problems and limitations

In my experience implementing this functionality, there are several traps that don't always appear in official documentation and that I can save you from:

  1. Ranges chopped up by internal elements
    1. If your paragraph has internal <span>s, the range is sometimes generated from the <span> rather than the full paragraph. This breaks bubble position calculations and any other operation needing absolute coordinates within the paragraph.
  2. Usage in <input> or <textarea>
    1. window.getSelection() does not work properly in Firefox or Edge Legacy for content inside <input> and <textarea>. The solution in those cases is to use setSelectionRange() or directly read the element's selectionStart and selectionEnd properties.
  3. Reconstruction of saved ranges
    1. For persistent notes or highlights (surviving a page refresh), the best approach is to save the parent node's id, start, end, and an excerpt of the selected text. With that data you can recreate the Range later without fragile dependencies.

How to record the range, highlight text, and create note bubbles

If you want the highlight to persist across sessions, you need to save the range information before the user navigates to another page. In my implementation, I send it to the backend via Axios like this:

this.$axios
.post(this.$root.urls.bsnCreate + this.section.id, {
  title: this.form.title,
  content: this.form.content,
  json: {
    text: this.bubbleSelectecOptions.selectionText.substring(0, 10),
    id: this.bubbleSelectecOptions.selectionId, // Save parent element ID
    start: this.bubbleSelectecOptions.selectionRangeStart,
    end: this.bubbleSelectecOptions.selectionRangeEnd
  }

To position the bubble right above the selected text, I use getBoundingClientRect() on the range to get exact screen coordinates:

const rect = rango.getBoundingClientRect();

posX = rect.left + window.scrollX;
posY = rect.top + window.scrollY - 40;

Then, I build a dynamic <span> wrapping the selected text and apply the highlighting style:

const span = document.createElement("span");
span.title = "My note";
span.className = "bg-purple-700 rounded-sm no-set-note text-white";

And best of all: if I saved the range earlier, I can reconstruct it precisely later using the parent node's id and the stored offsets. Here is how I do it with document.createRange():

const node = document.querySelector("#" + id).firstChild;
const rango = document.createRange();
rango.setStart(node, start);
rango.setEnd(node, end);

Putting it all together, the complete addHighlights() function looks like this:

async addHighlights(id, start, end, noteTitle, noteContent) {
  // const node = document.querySelector("#" + id).firstChild.nodeValue
  if (id.trim() == "")
    return this.$toast.warning(this.$t('large.noteBookRangeNoValid'))

  const node = document.querySelector("#" + id).firstChild
  const rango = document.createRange();

  try {
    rango.setStart(node, start);
    rango.setEnd(node, end);

    const span = document.createElement("span");
    span.title = noteTitle;
    span.id = "_" + id;

    span.onclick = function () {
      this.bubbleSelectecOptions.titleNote = noteTitle
      this.bubbleSelectecOptions.contentNote = noteContent
      this.bubbleSelectecOptions.showModalNoteUser = true
      this.bubbleSelectecOptions.modalKey3 = Date()
    }.bind(this);

    span.className = "bg-purple-700 rounded-sm no-set-note text-white";

    rango.surroundContents(span);
  } catch (error) {
    console.error(error)
  }
},

Best practices and advanced tips

  • Handle partial nodes with care: surroundContents() throws an exception if your range includes incomplete nodes (for example, if the start and end of the range are in different nodes). Always wrap it in a try/catch block.
  • Cross-browser compatibility: test your implementation in Chrome, Firefox, Edge, and Safari, as getSelection() behavior with internal elements may vary slightly.
  • Optimization: avoid traversing the entire DOM every time you detect a selection. Work with the most specific parent node possible to improve performance, especially on pages with long content.
  • Persistence: always save the node's id, start and end offsets, and an excerpt of the original text. That excerpt will serve as extra verification to confirm the reconstructed range points to the correct text.

Frequently Asked Questions (FAQ)

  • 1. What is the difference between window.getSelection() and document.getSelection()?
    • Both return the same type of Selection object, but document.getSelection() always references the current document, whereas window.getSelection() can be used in wider window contexts, such as inside an <iframe>.
  • 2. How do I get the exact text of a range?
    • Use selection.toString() or range.toString() to get only plain text, without Selection object metadata.
  • 3. Why does it fail when internal elements like <span>s are present?
    • Because the range is generated from the innermost node found in the DOM, not the main container. The solution is to reconstruct it using the parent node's firstChild to anchor the offsets to the full paragraph.
  • 4. Can it be used in <input> or <textarea>?
    • In most browsers yes, but Firefox and Edge Legacy do not support it for these elements. In those cases, you must resort to setSelectionRange() and the selectionStart / selectionEnd properties directly on the DOM element.
  • 5. How to reconstruct saved ranges for persistent notes?
    • Save the node's id, start and end offsets, and a text excerpt. Then, upon reload, create a new Range() with document.createRange(), set its boundaries with setStart() / setEnd(), and apply surroundContents() to repaint the highlight.

Learn how to use window.getSelection() in JavaScript to detect selected text, reconstruct ranges using document.createRange(), and apply persistent highlights. Includes real-world examples and solutions for issues involving nested elements.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.