I need to process selected(highlighted with mouse) text in html page. But if I'm selecting ordered list <ol></ol> elements I'm losing numbering information. Maybe someone can help me with this information extraction, because if I select and copy+paste selection to text editor - I see those numbers. Function used for html fragment selection:
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
}
else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
Complete fiddle example : https://jsfiddle.net/t2mhcbyo/3/
Updated fiddle here. The main problem is that you are not, in fact, actually selecting the numbers. They cannot be selected. (You notice they don't get highlighted).
I suspect that when you are copying the list into a 'text' editor, you are actually copying html (which is an ordered list that has numbers), which the editor displays as an ordered list. When you copy into a plain text editor like notepad, wordpad, or just remove formatting, it will return to just the highlighted test.
To get the number at the start of the list items, you can store the information directly in the <li>
tags.
<li index="3">
Then, when you select the highlighted html, you can use a regex string replace to change the index to a number.
Example regex:
html = html.replace(/<li\ index="([0-9]+)">/g, "<li>$1. ");
<li index="3">
becomes <li>3.
This replaces the start list item tag that contains index information with a tag that has no information, but has a number at the start of the list.
Issue: This method puts a number at the start of every line, regardless of how much of the line is actually highlighted. You might be able to modify the regex to only replace some of the index="#"
's.