syntax | minimize xpath | select from code | Search

The convertXPathToCss function takes an XPath expression and converts it to a CSS selector, performing replacements such as removing // separators, replacing contains with attribute selectors, and rewriting descendant combinators. The function returns the converted CSS selector.

Cell 25


function convertXPathToCss(path) {
    // if matched xpath is simple enough, convert it to CSS
    // DIV[contains(@class, "product-tile")]/parent::*/DIV[2]//MD-CARD[contains(@class, "mat-card")]/parent::*/MD-CARD[1]
    return path
        .replace(/\/([a-z-]+)\[@id="(.*?)"]/ig, '/$1#$2')
        .replace(/\/([^\/]+)\[contains\(@class, "(.*?)"\)]/ig, '/$1.$2')
        .replace(/\/parent::[a-z-]+\/[a-z-]+\[([0-9]+)]/ig, ':nth-child($1)')
        .replace(/^\/\//ig, '')
        .replace(/\/\//ig, ' ')
        .replace(/\//ig, ' > ');
}


What the code could have been:

/**
 * Converts an XPath to a CSS selector.
 *
 * @param {string} path - The XPath to convert.
 * @returns {string} The equivalent CSS selector.
 */
function convertXPathToCss(path) {
    // Remove leading and trailing slashes
    path = path.trim().replace(/^\/+|\/+$/g, '');

    // Replace self-closing tags with their non-self-closing counterparts
    path = path.replace(/\/([a-z-]+)\[@id="(.*?)"]/ig, '/$1#$2');

    // Replace attribute contains function with CSS class
    path = path.replace(/\/([^\/]+)\[contains\(@class, "(.*?)"\)]/ig, '/$1.$2');

    // Replace parent axis with CSS nth-child pseudo-class
    path = path.replace(/\/parent::[a-z-]+\/[a-z-]+\[([0-9]+)]/ig, ':nth-child($1)');

    // Replace multiple slashes with a single space
    path = path.replace(/\/+/ig,'> ');

    // Remove remaining slashes and replace with spaces for readability
    path = path.replace(/\//ig,'> ');

    return path;
}

Function: convertXPathToCss

Parameters

Returns

Description

This function takes an XPath expression and converts it to a CSS selector.
It performs the following replacements:

  1. //div[@id="something"]/div -> div#something > div
  2. //div[contains(@class, "something")]/div -> div.something > div
  3. //parent::* div[2] -> nth-child(2) div
  4. Removes leading // and intermediate // separators
  5. Replaces any remaining // separators with >