window.getSelection() gives me the selected text, but I want the HTML window.getSelection() gives me the selected text, but I want the HTML javascript javascript

window.getSelection() gives me the selected text, but I want the HTML


Take a look at the DOM Range spec. You can get a Range from the user selection in Firefox using:

var range = window.getSelection().getRangeAt(0);

Note that some browsers, including Firefox, allow multiple selections, which can be accessed via the getRangeAt() method of the selection.

The Range is expressed in terms of DOM nodes and offsets within those nodes. Once you've got your Range, it's not straightforward to do exactly what you want, since the range's boundaries could be in different nodes at different levels of the DOM tree, so simply surrounding the Range's content with a tag is not always possible. You may be able to do something like the following, although it will create a new block element to contain the selected content:

var range = window.getSelection().getRangeAt(0);var selectionContents = range.extractContents();var div = document.createElement("div");div.style.color = "yellow";div.appendChild(selectionContents);range.insertNode(div);

Another, hacky, alternative is to use the execCommand() method of document to modify the selection (e.g. by setting it to a particular colour) and then using document.querySelectorAll or some selector library to select elements with that colour and then apply styling to them.


Tim Down's answer is on the right track. However one issue is that extractContents() will remove the selection from the dom. You can use

window.getSelection().getRangeAt(0).cloneContents(); 

to just get a copy of what's selected. You could then wrap that with your new tag and then replace the selection with it. Tim Down's concern about the range spanning multiple HTML elements is certainly a valid one. I think once you get the range, it 'fixes' up the html, but when you put it back in it could cause problems. Here's a good resource on the Range object.


window.getSelection() will return an object. You can use the returned selection object as a string by calling the objects .toString() method.

var selObj = window.getSelection();var selectedText = selObj.toString(); 

https://developer.mozilla.org/en/DOM/window.getSelection