Content Index
- What window.getSelection() is and how it works
- How to get the selected text in JavaScript
- The big problem with window.getSelection(): the cursed range
- Common problems and limitations
- How to record the range, highlight text, and create note bubbles
- Best practices and advanced tips
- Frequently Asked Questions (FAQ)
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:
anchorNodeandfocusNode: the start and end nodes of the selection, respectively.anchorOffsetandfocusOffset: 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 (usually1).
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, whereaswindow.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 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 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:
- Ranges chopped up by internal elements
- 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.
- If your paragraph has internal
- Usage in
<input>or<textarea>window.getSelection()does not work properly in Firefox or Edge Legacy for content inside<input>and<textarea>. The solution in those cases is to usesetSelectionRange()or directly read the element'sselectionStartandselectionEndproperties.
- Reconstruction of saved ranges
- 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 theRangelater without fragile dependencies.
- For persistent notes or highlights (surviving a page refresh), the best approach is to save the parent node's
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 atry/catchblock. - 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,startandendoffsets, 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()anddocument.getSelection()?- Both return the same type of
Selectionobject, butdocument.getSelection()always references the current document, whereaswindow.getSelection()can be used in wider window contexts, such as inside an<iframe>.
- Both return the same type of
- 2. How do I get the exact text of a range?
- Use
selection.toString()orrange.toString()to get only plain text, withoutSelectionobject metadata.
- Use
- 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
firstChildto anchor the offsets to the full paragraph.
- 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
- 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 theselectionStart/selectionEndproperties directly on the DOM element.
- In most browsers yes, but Firefox and Edge Legacy do not support it for these elements. In those cases, you must resort to
- 5. How to reconstruct saved ranges for persistent notes?
- Save the node's
id,startandendoffsets, and a text excerpt. Then, upon reload, create a newRange()withdocument.createRange(), set its boundaries withsetStart()/setEnd(), and applysurroundContents()to repaint the highlight.
- Save the node's