↑
Main Page
Interacting with IE range content
Interacting with IE range content
Interacting with a range’s content in IE is done through either the
text
property or the
pasteHTML()
method.
The
text
property, which you used previously to retrieve the text content of the range, can also be used
to set the text content of the range. For example:
var oRange = document.body.createTextRange();
oRange.findText(“Hello”);
oRange.text = “Howdy”;
If you run this code against the same
Hello World
code shown earlier, the resulting code is the following:
<p id=”p1”><b>Howdy</b> World</p>
Note that all the HTML tags remained intact when setting the
text
property. If you want to insert more
content than just plain text, you can use
pasteHTML()
to insert HTML code. For instance:
var oRange = document.body.createTextRange();
oRange.findText(“Hello”);
oRange.pasteHTML(“<em>Howdy</em>”);
If you run this code, the following is the resulting HTML :
<p id=”p1”><b><em>Howdy</em></b> World</p>
Collapsing an IE range
Ranges in IE have a
collapse()
method that works exactly the same as the DOM method: Pass in
true
to collapse the range to the beginning and
false
to collapse the range to the end.
oRange.collapse(true);
Unfortunately, no corresponding
collapsed
property tells you whether a range is already collapsed.
Instead, you must use the
boundingWidth
property, which returns the width (in pixels) of the range. If
boundingWidth
is equal to 0, the range is collapsed:
var bIsCollapsed = (oRange.boundingWidth == 0);
The
boundingHeight
,
boundingLeft
, and
boundingTop
properties also give information about the
range location, although these are less helpful than
boundingWidth
.
It is not recommended to use
pasteHTML()
when the range contains HTML code
because this causes unpredictable results and often results in improperly formed
HTML.
331
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 331
Free JavaScript Editor
Ajax Editor
©
→