Quiero crear un método que admita un tipo de elemento y cualquier cantidad de tipos de atributos. Por ejemplo,
createElement('div', {class: 'test-class', id: 'testId'})o
createElement('input', {class: 'test-class', id: 'myInput', type: 'button', onclick: 'console.log('hello world')'})Esto es lo que tengo hasta ahora, pero me preguntaba si hay una mejor manera de hacerlo.
function create(elementType, ...args) { const element = document.createElement(elementType); const [elementProps] = args; const { className, id, innerText, type, name, value, eventType, eventAction, } = elementProps[0]; for (let prop in elementProps[0]) { if (typeof prop !== 'undefined') { element.className = className; element.id = id; element.innerText = innerText; element.type = type; element.name = name; element.value = value; element.addEventListener(eventType, eventAction, false); } } return element; } function cEl(elementType, ...args) { const element = document.createElement(elementType); const elementProps = args[0]; for (const [key, value] of Object.entries(elementProps)) { if (typeof value != 'undefined') { if (key.indexOf('listener') == 0) { // Assume this is an event. element.addEventListener(key.substr(8), value, false); } else { element.setAttribute(key, value); } } } return element; } var el = cEl('input', { class: 'test-class', id: 'myInput', type: 'button', listenerclick: function(){console.log("hello world");} // Not a script but an actual function. }); document.getElementById('d').append(el); <div id="d"></div>Al eliminar la lista de atributos, la función ahora acepta cualquier cadena como atributo. dado que "on" puede aparecer en otros atributos, en este ejemplo lo he cambiado a un identificador más único.
En cuanto a la función en sí, depende de usted. Puede definir una función completa o un nombre de función. Simplemente no lo escriba como texto e intente convertirlo más tarde en código. Trate de evitar esto si puede.