How to get the selected word by double-clicking on div, p, span?

Can you get the word the user double clicked on? I tried in the onDblClick event handler, but selectStart is undefined; and the onselect event is apparently only available for TextArea.

+6
javascript html selection
source share
1 answer

You can use document.selection.createRange().text in IE and window.getSelection().toString() in firefox and webkit and attach to the ondblclick handler as follows:

 document.ondblclick = function () { var sel = (document.selection && document.selection.createRange().text) || (window.getSelection && window.getSelection().toString()); alert(sel); }; 

References

  • MSDN , for document.selection
  • MDN , for window.getSelection()
+8
source share

All Articles