使用javascript记录和检索html元素/节点路径 [英] record and retrieve html element / node path using javascript
问题描述
另外,如何通过索引路径选择span标签?
这将起作用。它以数组而不是字符串的形式返回路径。
根据您的请求更新。
您可以在这里查看: http:// jsbin .com / isata5 / edit (点击预览)
//获取一个节点的索引。
function getIndex(node){
var parent = node.parentElement || node.parentNode,i = -1,child;
while(parent&& child(child = parent.childNodes [++ i]))if(child == node)return i;
返回-1;
}
//获取一个节点的路径。
function getPath(node){
var parent,path = [],index = getIndex(node);
(parent = node.parentElement || node.parentNode)&& (路径=的getPath(父));
索引> -1&& path.push(索引);
返回路径;
}
//从路径中获取一个节点。
函数getNode(路径){
var node = document.documentElement,i = 0,index; ((index = path [++ i])> -1)node = node.childNodes [index];
while(
返回节点;
$ / code>
这个例子应该工作这个页面在你的控制台中。
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);
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?
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);
这篇关于使用javascript记录和检索html元素/节点路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!