I've created a personal API for creating elements for an HTML page. I would like feedback on efficiency, particularly in creating buttons and labels. Any and all feedback is appreciated and considered
tag.js
/*
* Shortcuts for creatings different tags
*/
function createLabel(text) {
let label_tag = document.createElement('label');
let label_tag_text = document.createTextNode(text);
tabel_tag.appendChild(label_tag_text);
return label_tag;
}
function createButton(type) {
/* need to manually add .onclick when creating button */
let button_tag = document.createElement('button');
button_tag.type = type;
return button_tag;
}
function createInput(type, id) {
let input_tag = document.createElement('input');
input_tag.type = type;
input_tag.id = id;
return input_tag;
}
function createDiv(id) {
let div_tag = document.createElement('div');
div_tag.id = id;
return div_tag;
}
function createTag(tag) {
/*
* Used for creating basic tags (<p>, <br>, <hr>, etc)
* Any tag that doesn't often use an ID, TYPE, NAME, CLASS, etc
*/
return document.createElement(tag);
}
1 Answer 1
You have a lot of repeated code. If you follow the same design you will end up with a huge list of create???()
functions
You could simplify to a single function, and pass tag name and an optional properties containing element and style properties.
const createTag = (tag, props = {}) => {
const style = props.style;
if (style) { delete props.style }
const el = Object.assign(document.createElement,props);
if (style) { Object.assign(el.style, style) }
return el;
}
Thus you can create tags
createTag("input", {type : "button", id : "buttonId"});
createTag("button", {value : "Click me"});
createTag("div", {textContent: "abc", id: "abcId", className: "abcDiv", style: {width: "10px"}});
If you did want to have a function to create each type then it would pay to put them together.
const createDOM = {
label(...
button(...
input(...
div(...
// and so on
}