fczbkk/css-selector-generator

Failed to execute 'querySelector' on 'Document': '<classname>' is not a valid selector.

tabjsina opened this issue · 1 comments

Creating a new issue for v2.0.0 (as recommended here: #18 (comment))

Problem

I am running into an issue in which class names along the tree contains are invalid for use by selectors. While class selectors do have name restrictions, class names do not, which could lead to errors when the targeted element is a child of an element that uses a classname that is invalid as a class selector.

Example

A reduced example that would trigger it:

HTML:

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <div class="valid-class-selector">
            <a href="/a0">Anchor0</a>
        </div>
        <div class="1-invalid-class-selector">
            <a href="/a1">Anchor1</a>
        </div>
    </body>
</html>

JS:

getCssSelector(document.querySelectorAll("a")[1]);

Error:

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Element': '.1-invalid-class-selector' is not a valid selector.

Possible fix

Taken from my original comment in the older issue: #18 (comment), would be to either wrap querySelectorAll in try/catch and return false:

try { result = root.querySelectorAll(selector); } catch { return false; }

or if you want to keep the functional logic clean of try/catch, another approach could be to add try/catch around the same selector against an empty document fragment

try { document.createDocumentFragment().querySelectorAll(selector); } catch { return false; }
result = root.querySelectorAll(selector);

@tabjsina Thank you for your report. The issue should be fixed now. Class names that start with a number will be ignored. Version 2.0.1 of this library contains the fix.