Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从元素到根JS的HTML路径_Javascript_Html - Fatal编程技术网

Javascript 从元素到根JS的HTML路径

Javascript 从元素到根JS的HTML路径,javascript,html,Javascript,Html,例如,我有这样的HTML <body> <div> something. </div> <div> something else </div> <div> <a> something. </a> <a> ELEMENT </a> </div> </body>

例如,我有这样的HTML

<body> 
   <div> 
     something. 
   </div> 
   <div> 
     something else 
   </div> 
   <div> 
     <a> something. </a>
     <a> ELEMENT </a> 
   </div> 
</body>
因此,对于元素,需要查看父节点,检查是否存在具有相同标记的兄弟节点,然后正确分配值并递归地将其分配给根节点

因此,对于元素,它是父根div的第二个a[1]子元素,它是body的第三个div[2]子元素


用JS有什么方法可以做到这一点吗?

这可能正是您想要的。否则我很抱歉我误解了你的问题

javascript: (function() {
    if ( typeof document.getElementsByTagName === 'function') {
        var elemTag = document.getElementsByTagName('input');
        for (var i = 0; i < elemTag.length; i++) {
            elemTag[i].addEventListener('mouseup', getPath);
        }
        var elemTag2 = document.getElementsByTagName('a');
        for (var j = 0; j < elemTag2.length; j++) {
            elemTag2[j].addEventListener('mouseup', getPath);
        }
        var elemTag3 = document.getElementsByTagName('select');
        for (var p = 0; p < elemTag3.length; p++) {
            elemTag3[p].addEventListener('mouseup', getPath);
        }
        var elemTag4 = document.getElementsByTagName('button');
        for (var m = 0; m < elemTag4.length; m++) {
            elemTag4[m].addEventListener('mouseup', getPath);
        }
        var elemTag5 = document.getElementsByTagName('img');
        for (var l = 0; l < elemTag5.length; l++) {
            elemTag5[l].addEventListener('mouseup', getPath);
        }
    }
    function getPath() {
        var domPathArr = [],
            elm,
            entry;
        elm = this;
        if ( typeof getIndex === "function" && elm) {
            entry = elm.tagName.toLowerCase() + "[" + getIndex(elm) + "]";
            if (entry) {
                domPathArr.push(entry);
                for ( elm = this.parentNode; elm; elm = elm.parentNode) {
                    entry = elm.tagName.toLowerCase();
                    if (entry === "html") {
                        break;
                    }
                    if (elm) {
                        entry += "[" + getIndex(elm) + "]" + "/";
                    }
                    domPathArr.push(entry);
                }
            }
        }
        domPathArr.reverse();
        console.log(domPathArr.join(' '));
    }

    function getIndex(elm) {
        var count = 0;
        if (elm) {
            for (var siblingElm = elm.previousSibling; siblingElm; siblingElm = siblingElm.previousSibling) {
                if (siblingElm.nodeName == elm.nodeName)
                    count++;
            }
        }
        return count;
    }

})(); 
<html>
    <head>
        <script>
            //Recursive function to get element path until html from passed element e;
            function getPath(e, d){
                d = (d || []);

                //if (!e || e.tagName === 'BODY'){ //Body is obivous in most cases tho.
                if (!e || !e.parentNode){
                    return d.join('/');
                }
                else{
                    //j is needed since <head> is previous sibling to <body> :s
                    for (var i = 0, n = e, j = 0; n = n.previousElementSibling; i++) if (n.tagName === e.tagName) j++;

                    //Here we add the element to the current path \o/
                    d.push(e.tagName.toLowerCase() + '[' + j.toString() + ']');
                    return getPath(e.parentNode, d);
                };
            };
        </script>
    </head>

    <body onclick = 'alert(getPath(this));'>
        <div>something.</div> 
        <div>something else</div> 
        <div> 
            <a onclick = 'alert(getPath(this));'>something.</a>
            <a onclick = 'alert(getPath(this));'>ELEMENT</a> 
        </div> 
    </body>
</html>

一种方法是:

function findIndexOfLike(node) {
  // creating an Array of the filtered children of the node's
  // parent element (using Array.prototype.filter() with
  // Function.prototype.call() to apply the Array method
  // to the Array-like collection):
  var children = Array.prototype.filter.call(node.parentNode.children, function(child) {

    // keeping only those elements that are of the same
    // tagName:
    return node.tagName === child.tagName;
  });

  // Using Array.prototype.indexOf() to find the index of
  // the node from the array of children; and returning that:
  return children.indexOf(node);

}

function createIndexedPathTo(node) {

  // an empty Array to contain the path:
  var path = [],

    // initialising the 'current' variable, which we'll
    // use to move upwards through the document:
    current = node;

  // while the node contained in the 'current' variable is
  // not the <body> element:
  while (current.tagName.toLowerCase() !== 'body') {

    // we push the lower-cased tagName of the 'current' node,
    // along with its index, to the array:
    path.push(current.tagName.toLowerCase() + '[' + findIndexOfLike(current) + ']');

    // move the 'current' variable to the parentNode of
    // the current element (to move 'up'):
    current = current.parentNode;
  }

  // there can be only one <body> element, but since
  // you seem to want it listed we add it here:
  path.push('body[0]');

  // now we reverse the array, and join it together,
  // with the '/' character, to form a string, returning
  // that formed string:
  return path.reverse().join('/');
}

// calling the function, passing it a DOM Node from which to start:
var route = createIndexedPathTo(document.querySelector('a:nth-child(2)'));

// setting the 'data-routeto' attribute of the <body>
// in order to display that route/path in the document
// using CSS generated content:
document.body.dataset.routeto = route;
身体::之前{ 显示:块; 内容:'路由到示例元素:'属性数据路由到; 颜色:999; } 某物 别的 某物 要素
可能是它的副本,但不是上面链接的副本。此PR搜索的方向与隐含的重复方向不同。您似乎忘记了包含解决方案的说明。抱歉,这是一个bookmarklet。当你按下元素时——这里我包括了输入、img、a和其他元素,你会得到路径
function findIndexOfLike(node) {
  // creating an Array of the filtered children of the node's
  // parent element (using Array.prototype.filter() with
  // Function.prototype.call() to apply the Array method
  // to the Array-like collection):
  var children = Array.prototype.filter.call(node.parentNode.children, function(child) {

    // keeping only those elements that are of the same
    // tagName:
    return node.tagName === child.tagName;
  });

  // Using Array.prototype.indexOf() to find the index of
  // the node from the array of children; and returning that:
  return children.indexOf(node);

}

function createIndexedPathTo(node) {

  // an empty Array to contain the path:
  var path = [],

    // initialising the 'current' variable, which we'll
    // use to move upwards through the document:
    current = node;

  // while the node contained in the 'current' variable is
  // not the <body> element:
  while (current.tagName.toLowerCase() !== 'body') {

    // we push the lower-cased tagName of the 'current' node,
    // along with its index, to the array:
    path.push(current.tagName.toLowerCase() + '[' + findIndexOfLike(current) + ']');

    // move the 'current' variable to the parentNode of
    // the current element (to move 'up'):
    current = current.parentNode;
  }

  // there can be only one <body> element, but since
  // you seem to want it listed we add it here:
  path.push('body[0]');

  // now we reverse the array, and join it together,
  // with the '/' character, to form a string, returning
  // that formed string:
  return path.reverse().join('/');
}

// calling the function, passing it a DOM Node from which to start:
var route = createIndexedPathTo(document.querySelector('a:nth-child(2)'));

// setting the 'data-routeto' attribute of the <body>
// in order to display that route/path in the document
// using CSS generated content:
document.body.dataset.routeto = route;