The Orca
The Orca

Reputation: 1250

How to find & retrieve a node position without relying on id, class or content in javascript

Context:

I tried a couple of things with childnodes but I failed so far.

Upvotes: 2

Views: 148

Answers (1)

levi
levi

Reputation: 25121

You can use the nodes position relative to its siblings to locate it within the dom. When dealing with nested elements, you simply prefix the nodes location with its parents location relative to its siblings. So you end up with a node identifier looking something like this: 2/0/4/1 Where each / corresponds to an additional level of depth. Here is a working example:

function getNodePosition(node){    
    var node = $(node);
    var result;
    var parent = node.parent();
    var siblings = parent.children();
    var pos = siblings.index(node);
    result = '/' + pos;

    if(parent.length && !parent.is('body')){
        result = getNodePosition(parent) + result;
    }
    return result;
}

function getNodeByPosition(position){
    var node = $('body');
    var layers = position.substring(1).split('/');
    $.each(layers, function(index, val){
        val = parseInt(++val);
        node = node.find(':nth-child(' + val +')')       
    });
    return node[0];
}

Jsfiddle

Upvotes: 2

Related Questions