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
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With