Skip to content

Instantly share code, notes, and snippets.

@leandroruel
Last active June 4, 2018 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leandroruel/4642172e1293ead45ae1e8e06a74c97b to your computer and use it in GitHub Desktop.
Save leandroruel/4642172e1293ead45ae1e8e06a74c97b to your computer and use it in GitHub Desktop.
function to create dinamically a element, first parameter, the tag name and the second a object of attributes { key: value }
// check if the attribute key is camelcase
const isCamelCase = (str) => {
return /[A-Z]/.test(str)
}
//change the attribute from camelcase to hyphen separator
const changeSeparator = (str) => {
return str.replace(/([a-zA-Z])(?=[A-Z])/g, '$1-').toLowerCase();
}
const elementCreator = (tagName, attributes = {}) => {
let el = document.createElement(tagName)
Object.entries(attributes).forEach((item, index) => {
if (isCamelCase(item[0])) {
item[0] = changeSeparator(item[0])
}
el.setAttribute(item[0], item[1])
})
return el
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment