Skip to content

Instantly share code, notes, and snippets.

@SvetlovNK
Last active July 15, 2017 22:56
Show Gist options
  • Save SvetlovNK/aa5db6efcb2d5bef094a444d0921fb88 to your computer and use it in GitHub Desktop.
Save SvetlovNK/aa5db6efcb2d5bef094a444d0921fb88 to your computer and use it in GitHub Desktop.
Create DOM element
function createElement(tag, props, ...children) {
const element = document.createElement(tag);
Object.keys(props).forEach(key => {
if (key.startsWith('data-')) {
element.setAttribute(key, props[key]);
} else {
element[key] = props[key];
}
});
children.forEach(child => {
if (typeof child === 'string') {
child = document.createTextNode(child);
}
element.appendChild(child);
});
return element;
}
/** Example creating html tag li
*
* const checkbox = createElement('input', { type: 'checkbox', className: 'checkbox', checked: todo.completed ? 'checked' : ''});
* const label = createElement('label', { className: 'title' }, todo.title);
* const editInput = createElement('input', { type: 'text', className: 'textfield'});
* const editButton = createElement('button', { className: 'edit'}, 'Изменить');
* const deleteButton = createElement('button', { className: 'remove'}, 'Удалить');
*
* const item = createElement('li', { className: `todo-item${todo.completed ? ' completed' : ''}`, 'data-id': todo.id }, checkbox, label, editInput, editButton, deleteButton);
*
* **/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment