I've already had this problem, and found the following explanation and implementation useful:
http://jsfiddle.net/VRcvn/
function surroundSelection(element) {
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(element);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
(taken from: Wrapping a selected text node with span)
EDIT:
to also change the style, here is a simple example
<p onmouseup="surroundSelection()">This is a text for testing the selection</p>
<script>
function surroundSelection() {
var span = document.createElement("span");
span.style.fontWeight = "bold";
span.style.color = "green";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}