I have a createEelement() function.
With her, I will create HTML elements.
Function code:
function createElement(tagName, options, ...children) {
const { classNames = [], attributes = {} } = options;
const elem = document.createElement(tagName);
for (let i = 0; i < classNames.length; i++) {
elem.classList.add(classNames[i]);
}
for (const attributePair of Object.entries(attributes)) {
const [attributeKey, attributeValue] = attributePair;
elem.setAttribute(attributeKey, attributeValue);
}
elem.append(...children);
return elem;
}
The function allows you to create items, hang classes and attributes. And also encourage all children to the item. Allows you to do it immediately when creating. I need to expand this feature in such a way that the event handlers can also be mounted. I plan to implement this in the options object.
My question is how can this be done? Considering that listeners may be more than one …
>Solution :
To resolve your problem, you could have an array of object, with the names of the events, the callbacks and the options of the event :
const listeners = [{
name: "onclick",
callback: (e) => e.preventDefault(),
options: {},
}];
(This is just an example)
Here is the result :
function createElement(tagName, options, ...children) {
const { classNames = [], attributes = {}, listeners = {} } = options;
const elem = document.createElement(tagName);
for (let i = 0; i < classNames.length; i++) {
elem.classList.add(classNames[i]);
}
for (const listener of listeners) {
elem.addEventListener(...listener);
}
for (const attributePair of Object.entries(attributes)) {
const [attributeKey, attributeValue] = attributePair;
elem.setAttribute(attributeKey, attributeValue);
}
elem.append(...children);
return elem;
}
Bonus
Here are some factorisation improvments :
function createElement(tagName, options, ...children) {
const { classNames = [], attributes = {}, listeners = {} } = options;
const elem = document.createElement(tagName);
// using a for...of loop
for (const className of classNames) {
elem.classList.add(className);
}
for (const listener of listeners) {
elem.addEventListener(...listener);
}
// destructuring instead of recreating two variables
for (const attributePair of Object.entries(attributes)) {
elem.setAttribute(...attributePair);
}
elem.append(...children);
return elem;
}
PS : I didn’t tested this code so it might not work, tell me if something is wrong.