Skip to content

fix(attributes): [attr~=""] with an empty value matches nothing#1810

Open
ursm wants to merge 1 commit into
fb55:masterfrom
ursm:fix/attr-includes-empty-value
Open

fix(attributes): [attr~=""] with an empty value matches nothing#1810
ursm wants to merge 1 commit into
fb55:masterfrom
ursm:fix/attr-includes-empty-value

Conversation

@ursm
Copy link
Copy Markdown

@ursm ursm commented Jun 2, 2026

Problem

The ~= (whitespace-separated "one of") attribute handler only short-circuits to boolbase.falseFunc when the value contains whitespace. An empty value falls through to the regex (?:^|\s)(?:$|\s), which matches an empty attribute — so [class~=""] wrongly selects elements with class="".

import * as CSSselect from "css-select";
import { parseDocument } from "htmlparser2";

const dom = parseDocument(`<i class=""></i>`);
CSSselect.selectAll('[class~=""]', dom); // ← returns the <i>, should be []

Expected behaviour

Per Selectors §6.3.2, an empty (or whitespace-containing) ~= value can never be a single token, so it represents nothing. Browsers agree — document.querySelectorAll('[class~=""]') returns nothing in Chrome.

This also makes ~= consistent with ^= / $= / *= (start / end / any), which already short-circuit empty values to falseFunc.

Change

Add value === "" to the existing short-circuit in the element (~=) handler, plus a test mirroring the existing empty-value tests for $= / *=.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Fixed attribute selector matching to properly handle empty string values as non-matching cases.
  • Tests

    • Added test coverage for attribute selectors with empty string values.

The `~=` handler only short-circuited to `falseFunc` for values containing
whitespace. An empty value fell through to a regex `(?:^|\s)(?:$|\s)` that
wrongly matched an empty attribute such as `class=""`.

Per Selectors §6.3.2 an empty (or whitespace-containing) `~=` value can never
be a single token and matches nothing — consistent with the empty-value
short-circuit `^=`/`$=`/`*=` already have, and with browser behaviour
(`[class~=""]` selects nothing in Chrome).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 2, 2026

Review Change Stack

📝 Walkthrough

Walkthrough

The PR extends the ~= attribute selector to treat empty string values as invalid matches. Previously, only whitespace-containing values were rejected. The implementation guard is updated with an explanatory comment, and test coverage confirms the new behavior.

Changes

Empty Attribute Value Handling

Layer / File(s) Summary
Empty attribute value guard and test
src/attributes.ts, test/attributes.ts
The attribute element selector guard now rejects both empty strings and whitespace-containing values via value === "" || whitespaceRe.test(value), with a clarifying comment and a new test asserting [foo~=''] compiles to boolbase.falseFunc.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

Poem

A rabbit hops through attributes so fine,
Empty strings? They'll never match, by design!
Whitespace rejected, now empties too,
Guard clauses gleaming, fresh and true. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main fix: handling empty values in the ~= attribute selector to match nothing, which is the core change across both modified files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/attributes.ts`:
- Around line 94-98: Add a runtime DOM test verifying that the selector
[foo~=''] yields no matches: in the "no matches" describe block (after the
existing compilation test using CSSselect._compileUnsafe and boolbase.falseFunc)
add a test that calls CSSselect.selectAll("[data-foo~='']", dom) and expects an
empty result (length 0) to confirm end-to-end behavior; reference the existing
dom fixture and use the same test structure as the case-insensitive tests for
consistency.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: b5d6c01f-d141-43b0-b163-e1396dac5132

📥 Commits

Reviewing files that changed from the base of the PR and between 4f8e62e and e2d2658.

📒 Files selected for processing (2)
  • src/attributes.ts
  • test/attributes.ts

Comment thread test/attributes.ts
Comment on lines +94 to +98
it("should for ~= with an empty value", () => {
expect(CSSselect._compileUnsafe("[foo~='']")).toBe(
boolbase.falseFunc,
);
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Consider adding a runtime DOM matching test for completeness.

The compilation test correctly verifies that [foo~=''] returns boolbase.falseFunc. However, consider adding a runtime test that verifies the selector returns no matches against actual DOM elements, similar to the case-insensitive tests in lines 78-84.

🧪 Suggested additional runtime test

Add this test case in the "no matches" describe block after line 98:

it("should not match elements for ~= with an empty value", () => {
    const matches = CSSselect.selectAll("[data-foo~='']", dom);
    expect(matches).toHaveLength(0);
});

This provides end-to-end verification that the selector behavior matches expectations against actual DOM.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/attributes.ts` around lines 94 - 98, Add a runtime DOM test verifying
that the selector [foo~=''] yields no matches: in the "no matches" describe
block (after the existing compilation test using CSSselect._compileUnsafe and
boolbase.falseFunc) add a test that calls CSSselect.selectAll("[data-foo~='']",
dom) and expects an empty result (length 0) to confirm end-to-end behavior;
reference the existing dom fixture and use the same test structure as the
case-insensitive tests for consistency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant