Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

record and retrieve html element / node path using javascript

Say I've selected a span tag in a large html document. If I treat the entire html document as a big nested array, I can find the position of the span tag through array indexes. How can I output the index path to that span tag? eg: 1,2,0,12,7 using JavaScript.

Also, how can I select the span tag by going through the index path?

like image 628
Rana Avatar asked Sep 24 '10 00:09

Rana


1 Answers

This will work. It returns the path as an array instead of a string.

Updated per your request.

You can check it out here: http://jsbin.com/isata5/edit (hit preview)

// get a node's index.
function getIndex (node) {
  var parent=node.parentElement||node.parentNode, i=-1, child;
  while (parent && (child=parent.childNodes[++i])) if (child==node) return i;
  return -1;
}

// get a node's path.
function getPath (node) {
  var parent, path=[], index=getIndex(node);
  (parent=node.parentElement||node.parentNode) && (path=getPath(parent));
  index > -1 && path.push(index);
  return path;
}

// get a node from a path.
function getNode (path) {
  var node=document.documentElement, i=0, index;
  while ((index=path[++i]) > -1) node=node.childNodes[index];
  return node;
}

This example should work on this page in your console.

var testNode=document.getElementById('comment-4007919');
console.log("testNode: " + testNode.innerHTML);

var testPath=getPath(testNode);
console.log("testPath: " + testPath);

var testFind=getNode(testPath);
console.log("testFind: " + testFind.innerHTML);
like image 160
Dagg Nabbit Avatar answered Oct 28 '22 15:10

Dagg Nabbit