faqts : Computers : Programming : Languages : JavaScript : Document

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

29 of 35 people (83%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I get the HTML markup of the current text selection?
How can I get the HTML markup of the current text selection?

Nov 30th, 2004 06:25
Martin Honnen,


MS IE (at least on Windows) allows you to create a range from
document.selection and such a range has a property named htmlText.
With Mozilla (and other Gecko browsers like Netscape 7 or Firefox) there
is no such property but the following example clones the range the
current selection is built from, inserts it into a HTML <div> element
and reads its innerHTML to get at the serialization (the HTML markup) of
the selection.
The example has been tested with IE 6 and Netscape 7.2 and Firefox 1.0
and should hopefully work with IE 5/5.5 and Mozilla 1.x too.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
          "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>The serialized HTML of a selection in Mozilla and IE</title>
<script type="text/javascript">
function getHTMLOfSelection () {
  var range;
  if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    return range.htmlText;
  }
  else if (window.getSelection) {
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
      range = selection.getRangeAt(0);
      var clonedSelection = range.cloneContents();
      var div = document.createElement('div');
      div.appendChild(clonedSelection);
      return div.innerHTML;
    }
    else {
      return '';
    }
  }
  else {
    return '';
  }
}
</script>
</head>
<body>
<div>
<p>Some text to test the selection on.
Kibology for <b>all</b>. All <i>for</i> Kibology.
</p>
</div>
<form action="">
<p>
<input type="button" value="show HTML of selection"
       onclick="this.form.output.value = getHTMLOfSelection();">
</p>
<p>
<textarea name="output" rows="5" cols="80"></textarea>
</p>
</form>
</body>
</html>