OpenC3/cosmos

View on GitHub
openc3-cosmos-init/plugins/packages/openc3-cosmos-ace-diff/src/dom/ensureElement.js

Summary

Maintainability
A
0 mins
Test Coverage
/**
 * Search for element in parent and create it if it can't be found
 * @param {*HTMLElement} parent
 * @param {string} elClass Element class
 *
 * Returns ID of the element
 */
export default function ensureElement(parent, elClass) {
  const guid = Math.random().toString(36).substr(2, 5)
  const newId = `js-${elClass}-${guid}`

  const currentEl = parent.querySelector(`.${elClass}`)
  if (currentEl) {
    currentEl.id = currentEl.id || newId
    return currentEl.id
  }

  const el = document.createElement('div')
  parent.appendChild(el)
  el.className = elClass
  el.id = newId
  return el.id
}