Parent中的Child DOM元素的索引

时间:2015-10-27 05:55:31

标签: javascript html

我正在寻找一种纯粹的JS方式来寻找孩子在其父母中的偏移。

鉴于以下样本:

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

我会得到3个孩子,brbspan。每个都需要在div的开头有一个偏移量 - 所以标签开头的div中有多少个字符的索引。
因此br的偏移量为2。

我最初的想法是获取div的所有children,然后以某种方式可以轻松获得索引。

1 个答案:

答案 0 :(得分: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;
}