使用javascript记录和检索html元素/节点路径 [英] record and retrieve html element / node path using javascript

查看:91
本文介绍了使用javascript记录和检索html元素/节点路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在一个大的HTML文档中选择了一个span标签。如果我把整个HTML文档当作一个大的嵌套数组,我可以通过数组索引找到span标签的位置。如何输出索引路径到该span标签?例如:1,2,0,12,7使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆