Get HTML Of Selection


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your 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. };

URL: http://oopstudios.com/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.