The current approach to generating CSS paths could be improved for accuracy and readability.
The original function:
var cssPath = function (el) { var path = []; while ( (el.nodeName.toLowerCase() != 'html') && (el = el.parentNode) && path.unshift(el.nodeName.toLowerCase() + (el.id ? '#' + el.id : '') + (el.className ? '.' + el.className.replace(/\s+/g, ".") : '')) ); return path.join(" > "); }
produces CSS paths like:
html > body > div#div-id > div.site > div.clearfix > ul.choices > li
For precision, the path should include nth-child() for elements without IDs:
html > body > div#div-id > div.site:nth-child(1) > div.clearfix > ul.choices > li:nth-child(5)
The following enhanced function addresses these issues:
var cssPath = function(el) { if (!(el instanceof Element)) return; var path = []; while (el.nodeType === Node.ELEMENT_NODE) { var selector = el.nodeName.toLowerCase(); if (el.id) { selector += '#' + el.id; path.unshift(selector); break; } else { var sib = el, nth = 1; while (sib = sib.previousElementSibling) { if (sib.nodeName.toLowerCase() == selector) nth++; } if (nth != 1) selector += ":nth-of-type("+nth+")"; } path.unshift(selector); el = el.parentNode; } return path.join(" > "); }
With this enhancement, the CSS path for the given element will be more precise and readable.
The above is the detailed content of ## How Can We Improve the Accuracy and Readability of CSS Paths?. For more information, please follow other related articles on the PHP Chinese website!