Dan Sorensen Dan Sorensen - 7 months ago 52
jQuery Question

How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?

How do I take a selection from window.getSelection().getRangeAt(0) and surround it with an HTML tag such as 'span' or 'mark'? I prefer a straight javascript or jQuery solution.

I am able to output the selected text using alert, but have not yet figure out how to surround it with additional markup. I have seen many examples of running execCommand on the selection, but that is not what I'm looking for.

See my working example at jsfiddle

Any ideas? Thanks

Answer Source

If the selected text is all contained within a single text node, you can use the surroundContents() method of the Range. However, that doesn't work in the general case. The thing to do is surround each text node within the Range in a <span>. My Rangy library has a module that does this and works cross-browser (IE <= 8 does not natively support DOM Range).

Example code using Rangy:

<style type="text/css">
    span.highlighted {
        background-color: yellow;
<script type="text/javascript">
    var highlightApplier;

    window.onload = function() {
        highlightApplier = rangy.createCssClassApplier("highlighted ", true);

    function applyHighlight() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download