I'm making a little WYSIWYG for a project, and I need the ability to highlight text, click a button, and that will append a span around the selection with a class of ".highlight". The span will have a yellow background.
This is what I have so far from elsewhere on SO which is appending text instead of HTML. http://jsfiddle.net/aGzvp/
Here's the JS:
function wrap(tag) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0);
selectedText = range.toString();
range.deleteContents();
range.insertNode(document.createTextNode('[' + tag + ']' + selectedText + '[/' + tag + ']'));
}
}
else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
selectedText = document.selection.createRange().text + "";
range.text = '[' + tag + ']' + selectedText + '[/' + tag + ']';
}
}