Snippet – Get selected text or selected html in a div using jquery
Introduction
Snippet – Get selected text or selected html in a div using jquery very easily.
Get Selected Html of div
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; }
Get Selected text of div
function getSelectionText() { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }
The selection of text can be done by double click with a mouse on text, or just select the text with mouse drag. The methods work for both types.
Conclusion
Very quick and easy snippets often forget to document, taking time to put in the post for reference. Hope it helps any one looking for a working methods
October 16, 2015
В·
Adi В·
No Comments
Posted in: Asp.Net, Sharepoint 2010, SharePoint 2013
Leave a Reply