Skip to content

[a~=""] matches elements #1910

Closed
Closed

Description

@robertmorelli

issue:
Per the spec, ~= with an empty value matches nothing. css-select matches a="" and values with leading, trailing or doubled spaces.

repro:

import { selectAll } from "css-select";
import { parseDocument } from "htmlparser2";
const doc = parseDocument('<i a=""></i><i a=" x"></i><i a="x "></i><i a="x  y"></i>');
console.log(selectAll('[a~=""]', doc).length); // 4

expected:
prints 0 (as Chrome, Firefox, Safari)

system:
css-select 7.0.0, Node 25.8.1
macOS 27.0, arm64

Activity

  1. NevanDeCoteau commented on Oct 13, 2026

    @NevanDeCoteau
    Contributor

    Hi. I think this would be a good fit for my first open-source contribution. I’m new to css-select and its codebase, but I’d like to try this issue if it’s still available.

  2. visualkhh commented on Oct 31, 2026

    @visualkhh

    Ran into this class and pinned the exact line — the gap is visible by comparing the four sibling rules in src/attributes.ts.

    Browser (Chromium, full empty-value matrix). On <i a="">, <i a=" x">, <i a="x">, <i a="-x">:

    • [a~=""] → 0, [a|=""] → 2 (a="" and a="-x"), [a^=""] → 0, [a$=""] → 0, [a*=""] → 0
    • sanity: [a~="x"] → 3, [a~="y"] → 1, [a=""] → 1, [a] → 4

    So ~=/^=/$=/*= with an empty value never match, while |= keeps dash-list semantics.

    Source. start (^=), end ($=), and any (*=) all early-return boolbase.falseFunc on empty values — but element (~=) only rejects whitespace-containing values (if (whitespaceRe.test(value))) and has no empty check. With value === "", its regex becomes (?:^|\s)(?:$|\s), which matches "", " x", "x ", and even "x y" (whitespace in the middle satisfies both anchors) — hence 4/4. hyphen (|=) is already correct via its length === 0 path.

    The fix is one line — extend that guard to if (value === "" || whitespaceRe.test(value)), mirroring the three siblings.

    Amusing footnote: I hit the mirror-image gap in what I use (@dooboostore/dom-parser) — the empty guard there covered ^=/$=/*= but was missing ~= (''.split(/\s+/) contains ''), so [a~=""] matched 3/4. Same one-line shape, and I verified 0/3/2/0/0/1 against Chromium on my setup.

  3. added a commit that references this issue on Nov 6, 2026
    ca67a21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions