How do I create a range object when I know just the character offsets?

10,453

A Range boundary is not a character offset within a string representation of HTML. Rather, it is an offset within a DOM node. If the node is a text node, for example, the boundary is expressed as a character offset within the node's text. If the node is an element, it is expressed as the number of child nodes of the node prior to the boundary. For example, in the following HTML, with a Range whose boundaries are denoted by |:

<div id="test">foo|bar<br>|<br></div>

... the range's start boundary lies at offset 3 in the text node that is the first child of the <div> element, while the end boundary lies at offset 2 within the <div>, since there are two child nodes (text node "foobar" and one <br> element) lying before the boundary. You would create the range programmatically as follows:

var range = rangy.createRange(); // document.createRange() if not using Rangy
var div = document.getElementById("test");
range.setStart(div.firstChild, 3);
range.setEnd(div, 2);
Share:
10,453

Related videos on Youtube

Adim
Author by

Adim

Updated on June 05, 2022

Comments

  • Adim
    Adim almost 2 years

    So I have a div that contains a block of text, previously the user has selected some text in this block and I created a range object from this selection. I stored the offset of the selected text's starting and ending points but I am having problems re-creating the range (so i can manipulate it). "quotables" is the div that holds all the text. I dont know what I am doing wrong.

    
    
        var theRange = rangy.createRange();
        var node = $('.quotables').html();
        theRange.setStart(node, 14);
        theRange.setEnd(node, 318);
    
    
    

    but I keep getting errors: Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
    m.setStart
    (anonymous function)
    d.extend._Deferred.f.resolveWith
    d.d.extend.ready
    d.c.addEventListener.y

    • Mike Turley
      Mike Turley about 12 years
      Did you ever figure out a good solution to this problem? I'm trying to recursively iterate through text nodes and count characters, I feel like I'm almost there...
  • Mike Turley
    Mike Turley about 12 years
    Is there a way to programmatically "figure out" which start and end nodes and relative offsets you'd need given the character offsets within a string representation of the text?