UPDATE: Apparently, the problem I ran into affects only the first item in the selection.
JSFiddle: http://jsfiddle.net/NhQCR/
My code that makes a choice on a webpage:
if (!window.TB) { TB = {}; } TB.Selector = {}; // http://stackoverflow.com/questions/5643635/how-to-get-selected-html-text-with-javascript // and // http://stackoverflow.com/questions/7690319/javascript-how-do-i-expand-a-user-selection-based-on-html-tags TB.Selector.getSelected = function() { var html = ""; if (typeof window.getSelection != "undefined") { var sel = window.getSelection(); if (sel.rangeCount) { var range = sel.getRangeAt(0); var startEl = sel.anchorNode; if (startEl != range.commonAncestorContainer) { while (startEl.parentNode != range.commonAncestorContainer) { startEl = startEl.parentNode; } } var endEl = sel.focusNode; if (endEl != range.commonAncestorContainer) { while (endEl.parentNode != range.commonAncestorContainer) { endEl = endEl.parentNode; } } range.setStartBefore(startEl); range.setEndAfter(endEl); sel.addRange(range); var container = document.createElement("div"); container.appendChild(sel.getRangeAt(0).cloneContents()); html = container.innerHTML; } } else if (typeof document.selection != "undefined") { if (document.selection.type == "Text") { html = document.selection.createRange().htmlText; } } return html; }
and how to get the selected text:
var selected_text = TB.Selector.getSelected();
Unfortunately, as you can see in the figure, this method for selecting text removes certain space characters and adds an empty div at the end of the selection

Here is what the selection on the webpage looks like: 
For those who are wondering: this is how I got the warning to show what it is doing:
start_index = $j(".text_container").html().indexOf($selected_text); end_index = start_index + $selected_text.length; alert(start_index + " to " + end_index + "\n" + $selected_text + "\n=====================================\n" + $j(".text_container").html());
Currently, the select code will expand the selection to ensure that there are no inconsistent tags. I want a code that will get me exactly what is on the web page without deleting / adding anything = \ I just donβt know where to start = \
source share