1
\$\begingroup\$

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);
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Feb 21, 2019 at 21:27
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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
}
answered Feb 21, 2019 at 23:00
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.