Creating Accurate CSS Paths from DOM Elements
In JavaScript, constructing CSS paths from DOM elements is a common task. To address this, a popular function, cssPath, exists. However, it often produces paths that lack important details, such as nth-child selectors.
The provided code offers a solution:
<code class="js">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(" > "); };</code>
Improvements Over the Original Function:
The above is the detailed content of How to Generate More Accurate CSS Paths from DOM Elements in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!