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

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;
    }
</style>
<script type="text/javascript">
    var highlightApplier;

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

    function applyHighlight() {
        highlightApplier.applyToSelection();
    }
</script>

Leave a Comment