简体   繁体   中英

Index of Child DOM element within Parent

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM