Get CSS path from Dom element

前端 未结 6 1532
慢半拍i
慢半拍i 2020-11-27 16:08

I got this function to get a cssPath :

var cssPath = function (el) {
  var path = [];

  while (
    (el.nodeName.toLowerCase() != \'html\') && 
    (el = el         


        
6条回答
  •  粉色の甜心
    2020-11-27 16:28

    The two other provided answers had a couple of assumptions with browser compatibility that I ran into. Below code will not use nth-child and also has the previousElementSibling check.

    function previousElementSibling (element) {
      if (element.previousElementSibling !== 'undefined') {
        return element.previousElementSibling;
      } else {
        // Loop through ignoring anything not an element
        while (element = element.previousSibling) {
          if (element.nodeType === 1) {
            return element;
          }
        }
      }
    }
    function getPath (element) {
      // False on non-elements
      if (!(element instanceof HTMLElement)) { return false; }
      var path = [];
      while (element.nodeType === Node.ELEMENT_NODE) {
        var selector = element.nodeName;
        if (element.id) { selector += ('#' + element.id); }
        else {
          // Walk backwards until there is no previous sibling
          var sibling = element;
          // Will hold nodeName to join for adjacent selection
          var siblingSelectors = [];
          while (sibling !== null && sibling.nodeType === Node.ELEMENT_NODE) {
            siblingSelectors.unshift(sibling.nodeName);
            sibling = previousElementSibling(sibling);
          }
          // :first-child does not apply to HTML
          if (siblingSelectors[0] !== 'HTML') {
            siblingSelectors[0] = siblingSelectors[0] + ':first-child';
          }
          selector = siblingSelectors.join(' + ');
        }
        path.unshift(selector);
        element = element.parentNode;
      }
      return path.join(' > ');
    }
    

提交回复
热议问题