Using the TextRange Object


Posted in Javascript onOctober 14, 2006

Most users will only want to use the innerText/innerHTML and outerText/outerHTML properties and methods discussed previously. However, there is some more advanced text manipulation that can be done using a "text range" object. The TextRange object can be used to:  Locate the text for a given element or a given point.
Search for words and characters in the text of the document.
Move through the text in logical units.
Provide read/write access to the plain text and the HTMLText in the document.
This feature might not be available on non- Microsoft Win32 platforms. For the latest information on Microsoft Internet Explorer cross-platform compatibility, see article Q172976 in the Microsoft Knowledge Base.
This article consists of the following topics:

Overview of the TextRange Object
What Do I Do with a TextRange Object?
Positioning the TextRange Object
Creating a TextRange Object
Getting the Content of a TextRange
Comparing Ranges
Commands
Overview of the TextRange Object
Text range objects are an advanced feature of Dynamic HTML (DHTML) that you can use to carry out useful tasks related to dynamic content, such as searching for and selecting text. Text ranges let you selectively pick out characters, words, and sentences from a document. The TextRange object is an abstract object that creates a start and end position over the stream of text that would appear in the HTML document. Consider the following simple HTML document: 

<HTML>
<BODY>
<H1>Welcome</H1>
<CENTER><H2>Overview<H2></CENTER>
<P>Be sure to <B>Refresh</B> this page.</P>
</BODY>
</HTML>
In this document, creating a text range over the body element would position the start at the beginning of the textual content of the body, and the end at the end of the textual content of the body. This text range would contain the plain text "Welcome Overview Be Sure to Refresh this page." 

What Do I Do with a TextRange Object?
There are two parts to manipulating text with a TextRange object. The first is to create a text range so that the start and end positions encompass the desired text. The next step is to apply a method to the text range, or make a copy of the text to be used elsewhere in the document. Once the text range is positioned, you can search for text, select the text, and make a copy of the text and use it elsewhere in your document. 

See the TextRange object in the Object Model Reference for the properties and methods supported. 

Positioning the TextRange Object
Each text range has a start and an end position defining the scope of the text that is encompassed by the TextRange object. When you create a new text range, the start and end positions encompass the entire content by default. Use methods such as move, moveStart, and moveEnd to change the scope of the text range. 

Other methods can position the TextRange object with respect to a particular element, or a point on the page. For example, moveToElementText positions the text range so that it encompasses the text contained by the given element. The moveToPoint method positions the text range at a given point where the user clicked a mouse button. The x and y positions of the user's click are known by the window.event object and can be used to position the range over a given point. From this collapsed point, the range can then be expanded to encompass a word, sentence, or a whole textEdit (the entire possible TextRange object). 

Show Example

<HTML><HEAD>
<TITLE>moveToPoint Example</TITLE>
<script>
    function selectMe() {
    var r=document.body.createTextRange();
    r.moveToPoint(window.event.x, window.event.y);
    r.expand("word");
    r.select();
    }
</script>
</HEAD>
<BODY>

<H1 id=myH1 onclick=selectMe()>Click on a word and it will highlight</H1>

</BODY></HTML>
Show Me
Creating a TextRange Object
You create a TextRange object by applying the createTextRange method to a body, textArea, or button element. You can also create a text range from a selection made by the user. The createRange method on the selection object returns a text range. You can use the same methods and properties on this range as you do for ranges created using createTextRange. 

Creating a TextRange object on the body will not include the content inside a textArea or button. Conversely, you cannot change the start or end position of a text range over the textArea or button to move outside the scope of these particular elements. Use the properties provided on each element, isTextEdit and parentTextEdit, to walk the hierarchy. If the document above contained a textArea, a createTextRange on the body object would not find the position where the user actually clicked. The following reworks the above example to handle this case. 

Hide Example

<HTML><HEAD>
<TITLE>moveToPoint Example</TITLE>
<script for=document event=onclick>
     var r
     if(window.event.srcElement.isTextEdit)
           {
            r=window.event.srcElement.createTextRange();
     }else{
            var el=window.event.srcElement.parentTextEdit;
            r=el.createTextRange();
           }
     r.moveToPoint(window.event.x, window.event.y);
     r.expand("word");
     r.select();
</script>
</HEAD>
<BODY>

<H1 id=myH1>Click on a word and it will highlight</H1>

<TEXTAREA>
There's text in this element too that you could click on
</TEXTAREA>

</BODY></HTML>
Show Me
Getting the Content of a TextRange
The content of a TextRange object can be viewed with the text or htmlText property on the TextRange object. The text property is a read/write property that is similar to the innerText properties on the element objects, only this replaces the text encompassed by a TextRange object. 

The htmlText property is a read-only property that lets you examine the HTML that is contained within the start and end points of the TextRange object. To add rich HTML content to the text range, use the pasteHTML method. Although you can paste any HTML text that you want into a text range, the pasteHTML method does not preserve the hierarchy of the document, as do the innerHTML and outerHTML properties. Although pasteHTML won't fail if you paste invalid or inappropriate tags into the range, the resulting document might not look or behave the way you expect. If you paste an HTML fragment, the fragment is automatically closed to prevent it from affecting subsequent text and elements. For example, this means that if your scripts rely on ordinal positions in the document's all collection, after a pasteHTML, the sourceIndex into the document.all collection might point to a different element. 

Comparing Ranges
You can create more than one text range at a time, using them for independent, simultaneous access to different portions of the text in an element. You can also copy a text range by using the duplicate method. This is useful if you want temporary access to a portion of the original range but don't want to bother re-creating or restoring the original range. You can determine the relationship of one text range to another by using methods such as isEqual and inRange. 

Because the object model never holds on to a text range, you'll need to re-create any range whenever control leaves and then reenters your code. For example, any text range objects created by an event handler are discarded when the event handler returns. 

You can determine whether one range is entirely contained within another text range by using the inRange method. You can determine whether two text ranges are identical by using the isEqual method. Text ranges are identical if they start and end at exactly the same positions. Note that identical text ranges are always considered to be within one another, meaning the inRange method returns true for these. 

You can set the start or end point of a range to match the start or end point of another range by using the setEndPoint method. The method takes two parameters: a string describing which end points to transfer, and a range from which the source end point is taken. The following example sets the end of the range r1 to the start of r2. 

r1.setEndPoint( "StartToEnd", r2 )
You can also use StartToStart, EndToStart, and EndToEnd to set the end points. 

You can compare the start or end points of two ranges by using the compareEndPoints method. This method compares the end points and returns -1, 0, or 1, indicating whether the end point of the first range is less than, equal to, or greater than that of the second. 

A bookmark is an easy way to save the current start and end positions of a text range and quickly restore these positions when you need them. You create a bookmark for a given range by using the getBookmark method, which returns an opaque string that uniquely identifies the bookmark. (Opaque means the string cannot be examined or modified.) You use the string with the moveToBookmark method to move the text range back to the same start and end positions as when the bookmark was created. 

Commands
You can use commands to apply formatting and to carry out special actions on the text of a text range. You execute a command by using the execCommand method. You supply a command identifier and provide any additional command parameters. For example, you can change text to bold by using the Bold command as in the following Microsoft JScript (compatible with ECMA 262 language specification) example: 

var rng = document.body.createTextRange();
rng.collapse();
rng.expand("sentence");
rng.execCommand("Bold");
Show Me
The above example makes bold all text up to the first period in the document. 

Not all commands are available at all times. You can determine whether a command is available for a given text range by using the queryCommandEnabled and queryCommandSupported methods. For a list of commands, see Command Identifiers. 

To determine whether a given command has already been applied to a text range, use the queryCommandState method to retrieve the state of the command. The state is true if the command has been applied. 

Javascript 相关文章推荐
利用jQuery 实现GridView异步排序、分页的代码
Feb 06 Javascript
js向上无缝滚动,网站公告效果 具体代码
Nov 18 Javascript
JS实现鼠标单击与双击事件共存
Mar 08 Javascript
JS实现的验证身份证及获取地区功能示例
Jan 16 Javascript
js字符限制(字符截取) 一个中文汉字算两个字符
Sep 12 Javascript
node.js中使用Export和Import的方法
Sep 18 Javascript
vue.js动画中的js钩子函数的实现
Jul 06 Javascript
浅谈Redux中间件的实践
Jul 27 Javascript
关于单文件组件.vue的使用
Sep 20 Javascript
JQuery事件委托(适用于给动态生成的脚本元素添加事件)
Feb 01 jQuery
Vue Element校验validate的实例
Sep 21 Javascript
js实现复制粘贴的两种方法
Dec 04 Javascript
使用TextRange获取输入框中光标的位
Oct 14 #Javascript
JS代码格式化和语法着色V2
Oct 14 #Javascript
[原创]静态页面也可以实现预览 列表不同的显示方式
Oct 14 #Javascript
动态加载js文件 document.createElement
Oct 14 #Javascript
不错的asp中显示新闻的功能
Oct 13 #Javascript
简单JS代码压缩器
Oct 12 #Javascript
jQuery 1.0.2
Oct 11 #Javascript
You might like
浅析php设计模式之数据对象映射模式
2016/03/03 PHP
php在windows环境下获得cpu内存实时使用率(推荐)
2018/02/08 PHP
CCPry JS类库 代码
2009/10/30 Javascript
利用javascript实现全部删或清空所选的操作
2014/05/27 Javascript
IE6中链接A的href为javascript协议时不在当前页面跳转
2014/06/05 Javascript
JavaScript onkeypress事件入门实例(按下或按住一个键盘按键)
2014/10/17 Javascript
JavaScript实现的圆形浮动标签云效果实例
2015/08/06 Javascript
举例说明如何为JavaScript的方法参数设置默认值
2015/11/17 Javascript
JavaScript中eval()函数用法详解
2015/12/14 Javascript
jQuery实现的导航动画效果(附demo源码)
2016/04/01 Javascript
JS中mouseover和mouseout多次触发问题如何解决
2016/06/06 Javascript
jQuery+CSS3实现点赞功能
2017/03/13 Javascript
Vue中&quot;This dependency was not found&quot;问题的解决方法
2018/06/19 Javascript
Javascript格式化并高亮xml字符串的方法及注意事项
2018/08/13 Javascript
移动端(微信等使用vConsole调试console的方法
2019/03/05 Javascript
基于Element的组件改造的树形选择器(树形下拉框)
2020/02/27 Javascript
Vue使用预渲染代替SSR的方法
2020/07/02 Javascript
[05:09]2016国际邀请赛中国区预选赛淘汰赛首日精彩回顾
2016/06/29 DOTA
Python牛刀小试密码爆破
2011/02/03 Python
Python数据分析之真实IP请求Pandas详解
2016/11/18 Python
浅谈配置OpenCV3 + Python3的简易方法(macOS)
2018/04/02 Python
python 常用的基础函数
2018/07/10 Python
如何在Django项目中引入静态文件
2019/07/26 Python
Python3使用PySynth制作音乐的方法
2019/09/09 Python
Windows下PyCharm2018.3.2 安装教程(图文详解)
2019/10/24 Python
Python使用socketServer包搭建简易服务器过程详解
2020/06/12 Python
详解canvas.toDataURL()报错的解决方案全都在这了
2020/03/31 HTML / CSS
乌克兰网上服装店:Bolf.ua
2018/10/30 全球购物
波兰最早的运动鞋精品店之一:Street Supply
2019/08/29 全球购物
企业管理毕业生求职信范文
2014/03/07 职场文书
史学专业毕业生求职信
2014/05/09 职场文书
师范学院毕业生求职信
2014/06/24 职场文书
企业安全生产责任书范本
2014/07/28 职场文书
2019关于垃圾分类处理的调查报告
2019/12/26 职场文书
pandas中DataFrame检测重复值的实现
2021/05/26 Python
MySQL约束(创建表时的各种条件说明)
2022/06/21 MySQL