govuk-frontend icon indicating copy to clipboard operation
govuk-frontend copied to clipboard

Add helper for creating DOM elements

Open romaricpascal opened this issue 1 year ago • 5 comments

What

Add a createElement (naming up for discussion) helper function to act as a shortcut for creating elements and assigning them attributes, props and/or children (scope to be defined). Something along the lines of the following (in a syntax more adapted to the browsers we support):

export function createElement (tagName, {attributes = {}, properties = {}, children = []} = {}) {
  const el = document.createElement(tagName)

  Object.entries(attributes).forEach(([attributeName, attributeValue]) => {
    el.setAttribute(attributeName, attributeValue)
  })
  
  // This can help set `innerHTML` for example
  Object.entries(properties).forEach(([propertyName, propertyValue) => {
  	el[propertyName] = propertyValue
  })

  children.forEach(child => {
    el.appendChild(child)
  })

  return el
}

Why

A lightweight version of such helper has been added to de-clutter tests for the CharacterCount internationalisation: https://github.com/alphagov/govuk-frontend/blob/character-count-i18n/lib/dom-helpers.mjs. The Accordion and CharacterCount create a few elements themselves when initialised which would get a bit leaner.

Who needs to work on this

Developers

Who needs to review this

Developers

Done when

  • [ ] Decision on whether the helper would be helpful is made
  • [ ] If positive, helper is added and used in the component's code

romaricpascal avatar Oct 03 '22 13:10 romaricpascal