Reputation: 4761
I have the following HTML markup:
<body>
<div class="wrapper">
<div class="head">
<p class="title">title</p>
<a href="#" class="logo"></a>
</div>
</div>
</body
I need to get something like the following - the "A" element with class "logo" is the seconde childNode of the div element with class "head". The div element with class "head" is the first childNode of the div element with class "wrapper", the div element with class "wrapper" is the first childNode of body. Then I would get the location of the link with class "logo" as follows:
var a = [1, 1, 2]
So, if I go in the opposite direction using the array above, I will find the link with class "logo" in the DOM starting from the body element. Could anybody tell me how can this be achieved with JavaScript?
Thanks in advance.
Upvotes: 1
Views: 260
Reputation: 169391
Given the following HTML:
<body>
<div class="wrapper">
<div class="head">
<p class="title">title</p>
<a href="#" class="logo"></a>
</div>
</div>
</body
var el = document.body; // body
var div = document.body.firstChild; // div.wrapper
el === div.parentNode; // body === body
var div2 = div.firstElementChild; // div.head
div2.parentNode.parentNode === el; // body === body
var p = div2.firstElementChild; // p.title
var a = p.nextElementSibling; // a.logo
div2.children[1] === a; // a === a
I'm not quite sure what your trying to achieve. But I recommend you just walk the tree rather then construct relation ships in some kind of array.
Upvotes: 1
Reputation: 324567
Here's a pair of functions adapted from some existing code of mine to turn a node into an array of nested positions within a node and back again.
Live demo: http://jsfiddle.net/DSNUv/
Code:
function getNodeIndex(node) {
var i = 0;
while( (node = node.previousSibling) ) {
i++;
}
return i;
}
function nodeToPath(node, rootNode) {
var path = [], n = node;
rootNode = rootNode || document.documentElement;
while (n && n != rootNode) {
path.push(getNodeIndex(n));
n = n.parentNode;
}
return path;
}
function pathToNode(path, rootNode) {
rootNode = rootNode || document.documentElement;
var node = rootNode;
var i = path.length, nodeIndex;
while (i--) {
nodeIndex = path[i];
if (nodeIndex < node.childNodes.length) {
node = node.childNodes[nodeIndex];
} else {
throw new Error("Child node index out of range: " + nodeIndex);
}
}
return node;
}
Example use:
var a = document.getElementsByTagName("a")[0];
var path = nodeToPath(a, document.body);
alert(path);
var el = pathToNode(path, document.body);
alert(el.className);
Upvotes: 2