Posted By

optimal on 01/05/09


Tagged

html selection


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ductungdao


Get HTML Of Selection


 / Published in: JavaScript
 

URL: http://oopstudios.com/

Again, as part of the DCODR development I had to find a decent way to get the selection HTML

  1. getSelectionHTML = function () {
  2. var userSelection;
  3. if (window.getSelection) {
  4. // W3C Ranges
  5. userSelection = window.getSelection ();
  6. // Get the range:
  7. if (userSelection.getRangeAt)
  8. var range = userSelection.getRangeAt (0);
  9. else {
  10. var range = document.createRange ();
  11. range.setStart (userSelection.anchorNode, userSelection.anchorOffset);
  12. range.setEnd (userSelection.focusNode, userSelection.focusOffset);
  13. }
  14. // And the HTML:
  15. var clonedSelection = range.cloneContents ();
  16. var div = document.createElement ('div');
  17. div.appendChild (clonedSelection);
  18. return div.innerHTML;
  19. } else if (document.selection) {
  20. // Explorer selection, return the HTML
  21. userSelection = document.selection.createRange ();
  22. return userSelection.htmlText;
  23. } else {
  24. return '';
  25. }
  26. };

Report this snippet  

You need to login to post a comment.