Reputation: 1250
Context:
I need to keep the node selection of an user & be able to retrieve it later.
If there is an id on the html node I will use it.
But the problem arrive when there is no ID. I need to be able to mark this node & be able to find it back even after a page refresh.
I tried a couple of things with childnodes but I failed so far.
Upvotes: 2
Views: 148
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];
}
Upvotes: 2