Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Getting the starting index of selected text
/*
* Gets the starting index of the selected text
*/
function _getSelectionHtml() {
/*
* Returns HTML String of current selection
*/
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;
}
// Get all the html in your text container
var textContainerHtml = $('.myTextContainer').html();
// Get the the html string that was selected using the above function
var selectedHtml = _getSelectionHtml();
// Set the starting and ending index
var index = -1;
var endex = -1;
if (selectedHtml) {
index = textContainerHtml.indexOf(selectedHtml);
endex = index + selectedHtml.length;
}
@gfmclean

This comment has been minimized.

Copy link

commented Nov 6, 2018

This is assuming that the text selected is unique withing the container.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.