Home > Web Front-end > CSS Tutorial > ## How Can We Improve the Accuracy and Readability of CSS Paths?

## How Can We Improve the Accuracy and Readability of CSS Paths?

Patricia Arquette
Release: 2024-10-25 11:14:30
Original
878 people have browsed it

## How Can We Improve the Accuracy and Readability of CSS Paths?

CSS Path from Document Element: Enhanced Approach

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(" > ");
}
Copy after login

produces CSS paths like:

html > body > div#div-id > div.site > div.clearfix > ul.choices > li
Copy after login

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)
Copy after login

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(" > ");
 }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template