gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 09:28:18 25 4
gpt4 key购买 nike

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

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

最佳答案

这会起作用。它将路径作为数组而不是字符串返回。

根据您的要求进行更新。

您可以在这里查看: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;
}
<小时/>

此示例应该适用于您控制台中的此页面。

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 - 使用 javascript 记录和检索 html 元素/节点路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14015869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com