Double-click a word or select text in this paragraph, then double-click to highlight the current selection.
Return to Double click tutorial
const paragraph = document.getElementById('selectionText');
const status = document.getElementById('selectionStatus');
paragraph.addEventListener('dblclick', () => {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {
status.textContent = 'No text selection is available to highlight.';
return;
}
const range = selection.getRangeAt(0);
const mark = document.createElement('mark');
try {
range.surroundContents(mark);
selection.removeAllRanges();
status.textContent = 'Selected text highlighted.';
} catch (error) {
status.textContent = 'Select text within a single text section and try again.';
}
});<p id="selectionText" class="text-primary">Double-click a word or select text in this paragraph, then double-click to highlight the current selection.</p>
<p id="selectionStatus" aria-live="polite"></p>