Summary of textRange object usage methods in JavaScript

  • 2020-05-19 04:11:13
  • OfStack

The TextRange object is an advanced feature of dynamic HTML(DHTML), which enables you to perform many text-based tasks, such as searching and selecting text. The text range allows you to selectively select characters, words, and sentences from the document. The TextRange object is an abstract object that establishes the start and end positions on the text stream that the HTML document will display.

The following are the common properties and methods of TextRange:


boundingHeight gets the height of the rectangle that binds the TextRange object
boundingLeft gets the distance between the left edge of the rectangle that binds the TextRange object and the left side that contains the TextRange object
offsetLeft gets the calculated left position of the object relative to the layout or parent coordinates specified by the offsetParent property
offsetTop gets the computed top position of the object relative to the layout or parent coordinates specified by the offsetParent property
htmlText gets the width of the rectangle that binds the TextRange object
text sets or gets the text contained in the scope

moveStart changes the start of the scope
moveEnd changes the end of the scope
collapse moves the insertion point to the beginning or end of the current range
move folds a given range of text and moves the empty range by a given number of cells
execCommand executes commands on the current document, the current selection, or a given range
select sets the current selection area to the current object
findText searches the text in the text and sets the start and end points of the scope to surround the search string.
Using TextRange objects usually involves three basic steps:

1. Create a text range

2. Set the start and end points

3. Operate on the scope

<script language="javascript"> 
function moveCursor() 

    var temp = this.txtNum.value;  
     alert(" Please enter the 1 A digital "); 
    var rng = this.txtTest.createTextRange(); 
<input type="text" name="txtTest" value=" Ming luo guanzhong, 3 The romance of the nation 2101 Back to the Cao cao : "A hero is a man who is ambitious, who has good plans in his belly, who has the opportunity to harbor the universe, and who has the aspiration of heaven and earth. " size="100"><br> 
Move the cursor to point <input type="text" name="txtNum" size="5"> A position  
<input type="button" name="btnMove" value=" mobile " onclick="moveCursor()">  

1. createTextRange ()

Create an TextRange object, which is supported by BODY, TEXT, TextArea, BUTTON, and other elements. This method returns an TextRange object.

2. move (" Unit "[count])

The move() method performs two operations. First, the method overlaps the current document at the position of the first end point, which is used as an insertion point. In the next step, it moves the insertion point forward or backward by any character, word, or sentence unit.

The first argument to the method is a string, which specifies units such as character(character), word(word), sentence(paragraph), and textedit. The textedit value moves the insertion point to the end of the entire text range (no arguments are required). If you specify the first three units, the default value is 1 when the parameters are ignored, or you can specify an integer value to indicate the number of units, with positive Numbers representing forward movement and negative Numbers representing backward movement.

Note that the scope is still overlapping after the move() method is executed.

3. select ()

The select() method selects the text within the current text range, which the display cursor here must also use, because the so-called "cursor" can be understood as a range of overlapping boundaries

<textarea name="txtBox" rows="7" cols="50" id="txtBox"> 
chrysanthemum ( Curse of the golden flower theme song )  
Singer: jay Chou Album: still fantasia   
Your tears Weak with a wound   
The pale crescent moon Hook the past   
The night is too long Set into frost   
Who is in the attic of cold despair   
The rain gently drip Vermilion Windows   
I 1 In the paper The wind blow   
Dream in the distance into 1 Ray of chardonnay   
The wind blows You look like   
Chrysanthemum bleak injury Your smile has turned yellow   
Flowers fall to the heart My mind is still   
The north wind and the night are still young Your shadow keeps cutting   
Leaving me alone on the lake with frost   
<input type="text" value=" Enter what you want to query " id="txtFind"> 
<input type="button" value=" To find the 1 a " onclick="findText(txtFind.value)"> 
<script language="javascript"> 
var rng = txtBox.createTextRange(); 
function findText(str) 

   // define 1 The variables, as moveStart() The offset of the function, where the starting point skips the selected text  
   var num = 0; 
     num = document.selection.createRange().text.length; 
       // Each time the function is called, the end point is the end, and the start point is the new start point after skipping the selected text   
       // After searching, select the text   
   // If the final range of the search is still not found, the search is prompted to complete and resume rng Initial range ( Otherwise the new search cannot be performed )    
       alert(" After the search "); 
       rng = txtBox.createTextRange(); 

The above example demonstrates the selection range using the moveStart() and moveEne() methods. Several of the methods that appear are explained as follows:

4. moveStart (" Unit "[count]) and moveEnd (" Unit" [count])

The moveStart() and moveEnd() methods are similar to the move() methods, with the default start point being the first character of the container and the end point being the last character

We can modify the selectText() function above to prove:

function selectText()
  var rng = txtBox.createTextRange();

Move the start point one character forward and the end point one character back, and you can see that the range selected is the entire text range except for the first character and the last character.

5. collapse ([Boolean])

You can use the collapse() method to overlap the text range from the current size into a single insertion point between the characters. The optional parameter for the collapse() method is the Boolean value, which indicates whether the range overlaps at the beginning of the current range or at the end. The default value is true, which overlaps at the starting point:

6. findText (" searchString "[, searchScope, flags])

One of the most useful methods for the TextRange object is the findText() method, whose default behavior is to browse the text range from the start point to the end point, searching for a case-insensitive string match. If an instance is found in a scope, the start and end points of the scope are placed in this text, and the method returns true; Otherwise, return false with the start and end points unchanged. Method searches only the displayed text, and no tags or attributes are searched.

The optional parameter searchScope is an integer value indicating the number of characters from the starting point. Negative values force the search operation to search backwards from the current starting point.

The optional parameter flag is used to set whether the search is case-sensitive or if it matches only the entire word. The parameter is an integer value, which USES the mathematical method of combining bits to calculate a single value that can hold one or more Settings. The value matching the entire word is 2; The value of matching case is 4; If you only want to match 1, it is sufficient to provide only the desired value, but for both behaviors, the bit operator XOR (^ operator) is used to make the value 6.

findText () method is the most common applications include the scope of the search and replace operation, and formatting a string instance, because the search often begins with a range of current starting point, so the query again would like to move to the starting point to the range at the end of the match in the text (e.g., sample 3), after moving to make findText () continue to browse the rest of the text, to find the other one match. You can use the collapse(false) method to force the start point to move the end of the first matched range. So the findText() function for example 3 can also be modified to:

<script language="javascript">
var rng = txtBox.createTextRange();
function findText(str)
    // If the final range of the search is still not found, the search is prompted to complete and resume rng Initial range ( Otherwise the new search cannot be performed )  
     alert(" After the search ");
     rng = txtBox.createTextRange();

6. parentElement ()

The parentElement() method returns a reference that contains the text scope container

Gets the DOM object of the cursor selected text

function getParElem() 

    var rng = document.selection.createRange(); 
    var container = rng.parentElement(); 

This is only belonging to Body The text of the  
<div> This is included in div In the text of the </div> 
<p> This is included in p The text inside </p> 
<div><strong> This is included in div->strong In the text of the </strong></div> 
<input type="button" value=" Select the text and click " onClick="getParElem()"> 

Related articles: