A helper function which lets you create HTML DOM Element Objects where tagtype, ID and classes are set through basic CSS selector syntax. Pass an object with any arbitrary key value pairs as a second argument and this will set the element's other attributes. If a tagtype isn't defined a div is created.
createElement = (selectorName, attributes) ->
identifiers = selectorName.match /(?=^[a-z|A-Z]|\.|#).+?(?=\.|#|$)/g
identifiers =
tag : if (ref = identifiers[0]).charAt(0) not in [".", "#"] then ref else "div"
id : if (ref = identifiers.filter((str) => str.charAt(0) is "#")[0]) then ref.substring 1
classes : identifiers.filter((str) => str.charAt(0) is ".").map (str) => str.substring 1
element = document.createElement identifiers.tag
if (ref = identifiers.id) then element.id = ref
element.classList.add identifiers.classes...
element.setAttribute name, value for name, value of attributes
return element
Input fields often feature large quantities of attributes, an ID for a corresponding label and probably some classes to overwrite their hideous default styling.
input = createElement "input#address.input--wide.padding--xl",
"required" : ""
"type" : "text"
"name" : "address"
"placeholder" : "Your Home Address…"
document.body.appendChild input
input = document.createElement "input"
input.id = "address"
input.classList.add "input--wide", "padding--xl"
input.setAttribute "type" , "text"
input.setAttribute "name" , "address"
input.setAttribute "required" , ""
input.setAttribute "placeholder" , "Your Home Address…"
document.body.appendChild input
Saves you on the typing load and makes code more readable ❤