Last active
July 15, 2017 22:56
-
-
Save SvetlovNK/aa5db6efcb2d5bef094a444d0921fb88 to your computer and use it in GitHub Desktop.
Create DOM element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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