topical media & game development
professional-javascript-10-DOMRangeExample2.htm / htm
<html>
<head>
<title>DOM Range Example</title>
<script type="text/javascript">
function useRanges() {
var oRange1 = document.createRange();
var oRange2 = document.createRange();
var oP1 = document.getElementById("p1");
var iP1Index = -1;
for (var i=0; i < oP1.parentNode.childNodes.length; i++) {
if (oP1.parentNode.childNodes[i] == oP1) {
iP1Index = i;
break;
}
}
oRange1.setStart(oP1.parentNode, iP1Index);
oRange1.setEnd(oP1.parentNode, iP1Index + 1);
oRange2.setStart(oP1, 0);
oRange2.setEnd(oP1, oP1.childNodes.length);
document.getElementById("txtStartContainer1").value = oRange1.startContainer.tagName;
document.getElementById("txtStartOffset1").value = oRange1.startOffset;
document.getElementById("txtEndContainer1").value = oRange1.endContainer.tagName;
document.getElementById("txtEndOffset1").value = oRange1.endOffset;
document.getElementById("txtCommonAncestor1").value = oRange1.commonAncestorContainer.tagName;
document.getElementById("txtStartContainer2").value = oRange2.startContainer.tagName;
document.getElementById("txtStartOffset2").value = oRange2.startOffset;
document.getElementById("txtEndContainer2").value = oRange2.endContainer.tagName;
document.getElementById("txtEndOffset2").value = oRange2.endOffset;
document.getElementById("txtCommonAncestor2").value = oRange2.commonAncestorContainer.tagName;
}
</script>
</head>
<body><p id="p1"><b>Hello</b> World</p>
<input type="button" value="Use Ranges" onclick="useRanges()" />
<table border="0">
<tr>
<td>
<fieldset>
<legend>oRange1</legend>
Start Container: <input type="text" id="txtStartContainer1" /><br />
Start Offset: <input type="text" id="txtStartOffset1" /><br />
End Container: <input type="text" id="txtEndContainer1" /><br />
End Offset: <input type="text" id="txtEndOffset1" /><br />
Common Ancestor: <input type="text" id="txtCommonAncestor1" /><br />
</fieldset>
</td>
<td>
<fieldset>
<legend>oRange2</legend>
Start Container: <input type="text" id="txtStartContainer2" /><br />
Start Offset: <input type="text" id="txtStartOffset2" /><br />
End Container: <input type="text" id="txtEndContainer2" /><br />
End Offset: <input type="text" id="txtEndOffset2" /><br />
Common Ancestor: <input type="text" id="txtCommonAncestor2" /><br />
</fieldset>
</td>
</tr>
</table>
<p><strong>Note:</strong> This example uses DOM ranges and will only work in browsers that support DOM ranges. This example will fail in Internet Explorer.</p>
</body>
</html>
(C) Æliens
20/2/2008
You may not copy or print any of this material without explicit permission of the author or the publisher.
In case of other copyright issues, contact the author.