nntrn
4/20/2019 - 9:54 PM

[return or create html elements]

[return or create html elements]

// returns element based on query or builds if it doesnt currently exist
// buildOrReturnElement('div#notetags.spagon.d')
// will return this if it doesnt already exist:
// <div id="notetags" class="spagon d"></div>

function buildOrReturnElement(query) {
  var element = document.querySelectorAll(query);

  if (element.length > 0)
    return element[0]

  let elementAttr = query
    .match(/(\w+)|(#\w+-?\w*)|(.\w+-?\w*)/gi)
    .filter(Boolean)

  let buildNewElement = document.createElement(elementAttr.shift());
  let classArr = []
  elementAttr.forEach(e => {
    if (e.charAt(0) === "#")
      buildNewElement.id = e.substr(1, e.length)
    if (e.charAt(0) === ".")
      buildNewElement.classList.add(e.substr(1, e.length))
  })
  return buildNewElement
}