Good start, but he wants to be able to select text in a div. Try this:
HTML:
<div class="selectMe"> This is some text 'n stuff. Select part of me and cool stuff will happen! </div> <button id="highlight">Make Stuff Happen</button>
CSS:
.selectMe { margin-bottom: 2em; } button { cursor: pointer; } .highlight { background-color: red; }
JS:
if (!window.x) { x = {}; } x.Selector = {}; x.Selector.getSelected = function() { var t = ''; if (window.getSelection) { t = window.getSelection(); } else if (document.getSelection) { t = document.getSelection(); } else if (document.selection) { t = document.selection.createRange().text; } return t; } $(document).ready(function() { $("#highlight").click(function() { var selText = x.Selector.getSelected(); console.log(selText.focusNode); if (selText.focusNode.length > 0) { var para = $(".selectMe").text(); para = para.replace(selText, '<span class="highlight">' + selText + '</span>'); $(".selectMe").html(para); } else { } }); });