0

I'm looking for a pure JS way of finding the offset of a child within it's parent.

Given the below sample:

<div> A <br> short space elapsed, <b>and</b> up into this noiselessness came Ahab alone from his cabin. <span>Taking a few turns on the quarter-deck, he paused to gaze over the side</span> </div> 

I would get 3 children, a br, b, and span. Each would need to have an offset to the start of the div - So the index of how many characters into the div the start of the tag is.
So the br would have an offset of 2.

My initial idea was to get all the children of the div, then somehow from that be able to easily get an index.

10
  • What do you want is not clear as much. Commented Oct 27, 2015 at 5:57
  • why would the first child element have an offset of 2 - even considering it is the second child node, in a zero based language it makes no sense to give it an 'offset' of 2 Commented Oct 27, 2015 at 6:00
  • 1
    offset of 2 - 2px, 2em, 2cm...? Why 2? <br/> is not visible, how you see that offset? Is your offset same as padding/margin? What offset would be for any other childs? Commented Oct 27, 2015 at 6:03
  • Sorry, I assumed that seeing the HTML would mean we're dealing with HTML, not what the user can see. It would be the index? So how far along in the HTML does the actual tag start. I also said an offset to the start of the div. While that could be ambiguous, in my mind it made sense. Commented Oct 27, 2015 at 6:08
  • There may be more children than you expect. All nodes below an element are children, not just the element nodes. In this case, there could be 8 or more. Commented Oct 27, 2015 at 6:17

1 Answer 1

1
function getChildrenOffset(parent){ var childNodes = parent.childNodes; var childrenLocations = []; var offset = 0; var tagIndex = 0; for(var d = 0; d < childNodes.length; d++){ var node = childNodes[d]; if(node.tagName !== undefined){ // This is a tag tagIndex += 1; var curLocation = new OffsetData(offset, tagIndex, node.tagName); childrenLocations.push(curLocation); offset += node.outerHTML.length; }else{ // Just text offset += node.length; } } return childrenLocations; } function OffsetData(offset, index, tag){ this.Offset = offset; this.Index = index; this.TagName = tag; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.