Last active
June 4, 2018 15:07
-
-
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 }
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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