Skip to content

Instantly share code, notes, and snippets.

@ZhangChengX
Last active March 19, 2018 01:48
Show Gist options
  • Save ZhangChengX/26c2801476fd075d3a86e40664a72422 to your computer and use it in GitHub Desktop.
Save ZhangChengX/26c2801476fd075d3a86e40664a72422 to your computer and use it in GitHub Desktop.
Getting highlighted/selected text.
// Selection object
//var selection = window.getSelection();
var selection = window.getSelection ? window.getSelection() : document.selection;
// Selected plain text
var selected_text = selection.toString();
// Range object
var range = selection.getRangeAt(0);
// DocumentFragment
var fragment = range.cloneContents();
// Selected HTML
var div_wrapper = document.createElement("div");
div_wrapper.appendChild(fragment);
console.log(div_wrapper.innerHTML);
// Wrapping the selected text with span
var span_wrapper = document.createElement("span");
span_wrapper.setAttribute("class", "selected_text");
range.surroundContents(span_wrapper);
// Create a popup box inside the span
var popup_box = document.createElement("span");
popup_box.setAttribute('class', 'popup_box');
popup_box.innerHTML = text;
if (span_wrapper.innerHTML.length > 0) {
span_wrapper.appendChild(popup_box);
}
// Remove selection
if (selection.removeAllRanges) {
selection.removeAllRanges();
} else if (selection.empty) {
selection.empty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment