Skip to content

Commit

Permalink
Change classMap to set classes correctly for SVGs (lit#932)
Browse files Browse the repository at this point in the history
The assignment to `element.className` in `classMap` was causing the
error `setting getter-only property "className"`.

According to [the SVG
specification](https://www.w3.org/TR/SVG11/types.html#InterfaceSVGStylable),
`className` is a read-only property. This differs from [`className` on
Element](https://developer.mozilla.org/en-US/docs/Web/API/Element/className),
which can be set.
  • Loading branch information
AdamVig authored and justinfagnani committed Jun 14, 2019
1 parent 238a436 commit 6b46e04
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -34,6 +34,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
* Adopt and upgrade template fragments after processing for parts ([#831](https://github.com/Polymer/lit-html/issues/831)).
* Fixed bindings with attribute-like expressions preceeding them ([#855](https://github.com/Polymer/lit-html/issues/855)).
* Fixed errors with bindings in HTML comments ([#882](https://github.com/Polymer/lit-html/issues/882)).
* Change `classMap` directive to set classes correctly on SVGs ([#930](https://github.com/Polymer/lit-html/issues/930)).

## [1.0.0] - 2019-02-05
### Changed
Expand Down
2 changes: 1 addition & 1 deletion src/directives/class-map.ts
Expand Up @@ -48,7 +48,7 @@ export const classMap = directive((classInfo: ClassInfo) => (part: Part) => {

// handle static classes
if (!classMapCache.has(part)) {
element.className = committer.strings.join(' ');
element.setAttribute('class', committer.strings.join(' '));
}

const {classList} = element;
Expand Down
11 changes: 10 additions & 1 deletion src/test/directives/class-map_test.ts
Expand Up @@ -17,7 +17,7 @@

import {ClassInfo, classMap} from '../../directives/class-map.js';
import {render} from '../../lib/render.js';
import {html} from '../../lit-html.js';
import {html, svg} from '../../lit-html.js';

const assert = chai.assert;

Expand Down Expand Up @@ -81,6 +81,15 @@ suite('classMap', () => {
assert.isFalse(el.classList.contains('foo'));
});

test('adds classes on SVG elements', () => {
const cssInfo = {foo: 0, bar: true, zonk: true};
render(svg`<circle class="${classMap(cssInfo)}"></circle>`, container);
const el = container.firstElementChild!;
assert.isFalse(el.classList.contains('foo'));
assert.isTrue(el.classList.contains('bar'));
assert.isTrue(el.classList.contains('zonk'));
});

test('throws when used on non-class attribute', () => {
assert.throws(() => {
render(html`<div id="${classMap({})}"></div>`, container);
Expand Down

0 comments on commit 6b46e04

Please sign in to comment.