Örom Loidl
Örom Loidl

Reputation: 386

Refer window.getSelection().extentOffset to a certain HTML element

The following code finds out the beginning of the user's selection, if the user e.g. selects the text "text", this is "18".

<p>I am some example text, you don't have to read it :P</p>

<script>
function findsel(){
    console.log(window.getSelection().baseOffset);
    // Returns 18
}
</script>

If the paragraph is interrupted ...

<p id="mytext">I am some <em>example</em> text, you don't have to read it :P</p>

<script>
function findsel(){
    console.log(window.getSelection().baseOffset);
    // Returns 1
}
</script>

... and the user selects "text" again, the selection's beginning will be "1", because it starts counting at the </em> tag.

Is there a way to refer the getSelection method to a certain element (#mytext in this case) so it starts counting a the beginning of this specified element and not at the last in-between node?

Upvotes: 3

Views: 1217

Answers (1)

Lukilas
Lukilas

Reputation: 176

The Selection object returned by getSelection() references two Nodes:

  • getSelection().anchorNode is the Node containing the position where the selection started (i.e. where the user mouse-downed initially).

  • getSelection().focusNode is the node containing the position where the selection ends (i.e. where the user released the mouse).

This means that the offsets of the same selection can be in reversed order, depending on where the user started the selection. Just something to keep in mind.

Now to your question: In html, all texts are text nodes. In your example, there are three text nodes:

  • I am some
  • example
  • text, you don't have to read it :P

So whatever you select, focusNode and anchorNode will point to one (or two) of these text nodes, while focusOffset and anchorOffset will start counting at the beginning of the respective text node.

As far as I can tell, there is no way to make the selection start counting at the beginning of the parent node <p>. You will have to do it yourself: You could calculate once the lengths of all text nodes. Then you identify the text node where the selection starts, and add the offset to the sum of lengths of all previous nodes. I would have to know more about what you are trying to accomplish to give you more advice.

Upvotes: 2

Related Questions