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>
(Answering my own question based on a similar question I found when I posted mine...)
The guys in this Q&A thread were on an interesting track. It just used a different format than I was looking for. Modifying their code, I was able to do the following:
<h3><a href="#" id="btnRange">Display Range</a> |
<a href="#" id="btnMark">Mark Range</a></h3>
<div contenteditable="true" id="editor">
This is sample text. You should be able to type in this box or select anywhere in this div and then click the link at the top to get the selected range.
</div>
<script type="text/javascript">
var btnDisplay = $("#btnRange"),
btnMark = $("#btnMark");
btnDisplay.click(function() {
alert(window.getSelection().getRangeAt(0));
return false;
});
btnMark.click(function() {
var range = window.getSelection().getRangeAt(0);
var newNode = document.createElement("mark");
range.surroundContents(newNode);
return false;
});
I could further abstract the code in the btnMark.click() function to accept a tag name and then create a row of buttons to markup the code with mark, pre, blockquote.
A working solution can be found here: http://jsfiddle.net/3tvSL/