Get the DOM path of the clicked

后端 未结 8 1454
刺人心
刺人心 2020-11-30 06:01

HTML




         


        
8条回答
  •  忘掉有多难
    2020-11-30 06:36

    Here is a native JS version that returns a jQuery path. I'm also adding IDs for elements if they have them. This would give you the opportunity to do the shortest path if you see an id in the array.

    var path = getDomPath(element);
    console.log(path.join(' > '));
    

    Outputs

    body > section:eq(0) > div:eq(3) > section#content > section#firehose > div#firehoselist > article#firehose-46813651 > header > h2 > span#title-46813651
    

    Here is the function.

    function getDomPath(el) {
      var stack = [];
      while ( el.parentNode != null ) {
        console.log(el.nodeName);
        var sibCount = 0;
        var sibIndex = 0;
        for ( var i = 0; i < el.parentNode.childNodes.length; i++ ) {
          var sib = el.parentNode.childNodes[i];
          if ( sib.nodeName == el.nodeName ) {
            if ( sib === el ) {
              sibIndex = sibCount;
            }
            sibCount++;
          }
        }
        if ( el.hasAttribute('id') && el.id != '' ) {
          stack.unshift(el.nodeName.toLowerCase() + '#' + el.id);
        } else if ( sibCount > 1 ) {
          stack.unshift(el.nodeName.toLowerCase() + ':eq(' + sibIndex + ')');
        } else {
          stack.unshift(el.nodeName.toLowerCase());
        }
        el = el.parentNode;
      }
    
      return stack.slice(1); // removes the html element
    }
    

提交回复
热议问题