Skip to content
7 changes: 7 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,13 @@ module.exports = {
jest: true
}
},
{
files: ['**/*.jsdom.test.{cjs,js,mjs}'],
env: {
jest: true,
browser: true
}
},
{
// Matches Puppeteer environment in jest.config.mjs
// to ignore unknown Jest Puppeteer globals
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createElement } from './create-element.mjs'

describe('createElement', () => {
it('creates an element of the specified type', () => {
const $element = createElement('input')

expect($element).toBeInstanceOf(HTMLInputElement)
})

it('sets all attributes', () => {
const $element = createElement('div', {
'data-polarity': 'reversed',
'data-confinement-beam': 'active'
})

expect($element).toHaveAttribute('data-polarity', 'reversed')
expect($element).toHaveAttribute('data-confinement-beam', 'active')
})

it('allows classes to be set by passing them as attributes', () => {
const $element = createElement('div', {
class: 'my-class'
})

expect($element).toHaveClass('my-class')
})
})
24 changes: 24 additions & 0 deletions packages/govuk-frontend/src/govuk/common/create-element.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Creates an element with the given attributes
*
* @internal
* @template {keyof HTMLElementTagNameMap} TagName
* @param {TagName} tagName - Type of element to create
* @param {{[key: string]: string}} [attributes] - Attributes to set on the element
* @param {Node[]} [children] - The list of child nodes for the element
* @returns {HTMLElementTagNameMap[TagName]} Created element
*/
export function createElement(tagName, attributes = {}, children) {
const el = document.createElement(tagName)
Object.entries(attributes).forEach(([name, value]) => {
el.setAttribute(name, value)
})

if (children) {
for (const child of children) {
el.appendChild(child)
}
}

return el
}
Loading
Loading