Skip to content

fix: reading an unset style property returns "" per CSSOM, not undefined#328

Open
magicismight wants to merge 1 commit into
WebReflection:mainfrom
magicismight:fix-unset-style-empty-string
Open

fix: reading an unset style property returns "" per CSSOM, not undefined#328
magicismight wants to merge 1 commit into
WebReflection:mainfrom
magicismight:fix-unset-style-empty-string

Conversation

@magicismight

Copy link
Copy Markdown

Problem

Reading a style property that isn't set returns undefined, but per CSSOM both the camel-cased property getter and getPropertyValue() must return the empty string for an unset property.

import { parseHTML } from "linkedom";
const { document } = parseHTML("<!doctype html><html><body></body></html>");
const el = document.createElement("p");

el.style.color;                         // => undefined   (browser: "")
el.style.getPropertyValue("color");     // => undefined   (browser: "")

Because the property getter is routed through the same handler as getPropertyValue, both are affected. Code that assumes the spec — e.g. el.style.color.replaceAll(...) or any string method — throws Cannot read properties of undefined on an element that simply hasn't set that property. This bites libraries that parse arbitrary HTML and read inline styles (ProseMirror's DOMParser, etc.).

Fix

Normalize an absent property to "" in the style getter (esm/interface/css-style-declaration.js), which also covers getPropertyValue. Setting/removing/serialization are untouched; a set property still returns its value, and cssText is unchanged.

const value = style.get(uhyphen(name));
return value === void 0 ? '' : value;

CJS is regenerated via npm run cjs. A test is added in test/interface/css-style-declaration.js; the full suite (node test/index.js) passes.

Not a duplicate

Distinct from the open CSS issues:

Reading a property that is not set — via `el.style.someProp` or
`el.style.getPropertyValue("some-prop")` — returned undefined, but CSSOM
defines both as the empty string (the property getter is routed through the
same handler as getPropertyValue). Callers that assume the spec, e.g.
`el.style.color.replaceAll(...)`, crash on the undefined. Normalize an absent
property to "" in the style getter.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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