使用javascript记录和检索html元素/节点路径

Ran*_*ana 4 html javascript

假设我在大型html文档中选择了span标记.如果我将整个html文档视为一个大的嵌套数组,我可以通过数组索引找到span标记的位置.如何输出该span标记的索引路径?例如:1,2,0,12,7使用JavaScript.

另外,如何通过索引路径选择span标记?

Dag*_*bit 5

这会奏效.它将路径作为数组而不是字符串返回.

根据您的要求更新.

你可以在这里查看:http://jsbin.com/isata5/edit(点击预览)

// 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;
}
Run Code Online (Sandbox Code Playgroud)

此示例应在您的控制台中的此页面上运行.

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);
Run Code Online (Sandbox Code Playgroud)