Javascript: How to change the get select function so as not to remove extra spaces from the first DOM element in the select element?

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

enter image description here

Here is what the selection on the webpage looks like: enter image description here

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 = \

+4
source share
1 answer

I can’t reproduce the first problem, "empty space until 9", even when I use it. It may be due to encodings or to the little green guys. In any case, all my choices start from the right point.

For the second problem <div></div> at the end, just replace

 range.setEndAfter(endEl); 

by

 range.setEndBefore(endEl); 

It sounds like you select material in an array from 0 to length-1.

0
source

Source: https://habr.com/ru/post/1379148/


All Articles