Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.functiongetIndex (node) {
  varparent=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.functiongetPath (node) {
  varparent, 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.functiongetNode (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);

Solution 2:

Using jquery:

var tag = $('#myspan_id');
var index_path = [];
while(tag) {
  index_path.push(tag.index());
  tag = tag.parent();
}
index_path = index_path.reverse();

Solution 3:

Using the DOM

node = /*Your span element*/;
var currentNode = node;
var branch = [];
var cn; /*Stores a Nodelist of the current parent node's children*/var i;
while (currentNode.parentNode !== null)
    {
    cn = currentNode.parentNode.childNodes;
    for (i=0;i<cn.length;i++)
        {
        if (cn[i] === currentNode)
            {
            branch.push(i);
            break;
            }
        }
    currentNode = currentNode.parentNode;
    }
cn = document.childNodes;
for (i=0;i<cn.length;i++)
    {
    if (cn[i] === currentNode)
        {
        branch.push(i);
        break;
        }
    }
node.innerHTML = branch.reverse().join(",");

Solution 4:

composedPath for native event.

(function (E, d, w) {
    if (!E.composedPath) {
      E.composedPath = function () {
        if (this.path) {
          returnthis.path;
        }
        var target = this.target;

        this.path = [];
        while (target.parentNode !== null) {
          this.path.push(target);
          target = target.parentNode;
        }
        this.path.push(d, w);
        returnthis.path;
      };
    }
  })(Event.prototype, document, window);

use:

var path = event.composedPath()

Post a Comment for "Record And Retrieve Html Element / Node Path Using Javascript"