Main Page

Ranges

background-color: red;
padding: 10px;
}
</style>
<script type=”text/javascript”>
function useOuterText() {
var oDiv = document.getElementById(“div1”);
oDiv.outerText = oDiv.outerText;
alert(document.getElementById(“div1”));
}
</script>
</head>
<body>
<div id=”div1” class=”special”>This is my original text</div>
<input type=”button” value=”Use OuterText” onclick=”useOuterText()” />
</body>
</html>
When you click the button in this example, the
<div/>
is replaced with a text node containing
This is my
original text
. You can tell that the
<div/>
no longer exists by using
document.getElementById()
to
look for
div1
again. In this example, the result of the function (
null
) is displayed in an alert.
Ranges
To allow an even greater measure of control over a page, you can use something called a
range
. A range
can be used to select a section of a document regardless of node boundaries (note that the selection
occurs behind the scenes and cannot be seen by the user).
Ranges are helpful when regular DOM manipulation isn’t specific enough to change a document. And
as usual, there are two different implementations of ranges: one from the DOM and one from Internet
Explorer.
Ranges in the DOM
DOM Level 2 defines a method called
createRange()
to, well, create ranges. In DOM-compliant
browsers, this method belongs to the
document
object, so a new range can be created like this:
var oRange = document.createRange();
Just like nodes, a range is tied directly to a document. To determine if the document supports DOM-style
ranges, you can use the
hasFeature()
method discussed in Chapter 6, “DOM Basics.”
var supportsDOMRanges = document.implementation.hasFeature(“Range”, “2.0”);
The
outerText
and
outerHTML
properties are supported in Internet Explorer and
Opera only.
317
Advanced DOM Techniques
13_579088 ch10.qxd 3/28/05 11:39 AM Page 317


JavaScript EditorFree JavaScript Editor     Ajax Editor


©