From 92f477dc417997a8b924666e5ec4aae2d3d135ca Mon Sep 17 00:00:00 2001 From: Jeff Terrell Date: Thu, 27 May 2021 22:16:41 -0400 Subject: [PATCH] Merge classes from tag and attributes Before this commit, the following code: const h = require('hyperscript') h('.c1.c2', {class: 'c2 c3'}, 'Hello').outerHTML ...yields: '
Hello
' This is actually incorrect HTML according to the W3C Markup Validator [1] [1] https://validator.w3.org/#validate_by_input The correct output would of course be: '
Hello
' This commit achieves the correct output. --- index.js | 2 ++ test/index.js | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/index.js b/index.js index a3e2541..bd1b263 100644 --- a/index.js +++ b/index.js @@ -106,6 +106,8 @@ function context () { } else if (k.substr(0, 5) === "data-") { e.setAttribute(k, l[k]) + } else if (k === 'class') { + l[k].split(/\s+/).forEach(klass => ClassList(e).add(klass)) } else { e[k] = l[k] } diff --git a/test/index.js b/test/index.js index c007cc5..ee6178e 100644 --- a/test/index.js +++ b/test/index.js @@ -159,3 +159,10 @@ test('unicode selectors', function (t) { t.equal(h('span#⛄').outerHTML, '') t.end() }) + +test('classes from tag and attrs are merged', t => { + t.equal(h('.c1', {class: 'c2'}).outerHTML, '
') + t.equal(h('.c1.c2', {class: 'c3 c4'}).outerHTML, '
') + t.equal(h('.c1.c2', {class: 'c2 c3'}).outerHTML, '
') + t.end() +})