Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...