I want to create a method that takes in an element type and any number of attribute types. For example,
createElement('div', {class: 'test-class', id: 'testId'})
or
createElement('input', {class: 'test-class', id: 'myInput', type: 'button', onclick: 'console.log('hello world')'})
This is what I have so far but I was just wondering if there's a better way to do it
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>
By removing the attributes list the function now accepts any string as attribute. since "on" might appear in other attributes, In this example I've changed it into a more unique identifier.
As for the function itself, it's up to you. You can define a full function or a function name. Just don't write it as text and try to convert it later to code. Try to avoid this if you can.