Bernice
Bernice

Reputation: 2592

How can I get offset relative to grandparent elements in HTML?

If I have <p> some text <b> some oth|er text </b> bla bla </p> where the | is the caret and I want to get the offset relative to the p tag node, is there a way maybe I can find the offset relative to the p ?

Right now I am getting the offset of the selection by this:

var range = window.getSelection().getRangeAt(0); 
var offset = range.startOffset;

however this returns the offset relative to the bold tag.

I need this since I am developing an editor in Javascript and I need to implement the enter functionality myself since I am using this editor for real time collaboration. I found this problem when someone presses enter key in the middle of a child of the p tag.

Thanks for your help :)

Upvotes: 2

Views: 407

Answers (1)

plalx
plalx

Reputation: 43718

There are probably better ways to achieve this, but I haven't played enough with selections and ranges yet. However, I was thinking that since you already know the characters offset relative to the b tag, you would only have to add to the count the number of characters contained within text nodes that comes before the b tag to know the total offset.

I believe you could get the parent node of the b tag by doing something like, range.startContainer.parentNode.

Then, you could loop over the childNodes of the p tag until childNodes[i] is the b tag and each time you encounter a text node (node.nodeType === 3), you add node.textContent.length to the offset.

Upvotes: 1

Related Questions