el.js
About
This tool is made to make creation of elements easier. I was inspired by JSX and wanted to make something as easy to use and as easy to understand but something that would work in browser without compiling.
Guide
"__" function
It is document.createElement wrapper that makes creation of elements easier. Just look:
// __(tagname, options, children)
document.body.appendChild(
__('a', {
href: 'https://800147.github.io',
target: '_blank',
rel: 'noreferrer'
}, 'my link ^_^')
);
Array as children
Children can be not only string, but also another elements, numbers, booleans or array of acceptable values with any nesting
document.body.appendChild(
__('p', {}, [
'Is it ', true, ' that ', [
'there is ', 0, ' sugar in this ', __('b', {}, 'cookie')
], '?' ])
);
Components
You can make components by wrapping creating of element with function
const Item = (n) => __('li', {}, `item ${n}`);
document.body.appendChild(
__('ul', {}, [
Item(1),
Item(2),
Item(3)
])
);
Ignored children
All null, undefined and false values are ignored (but not the "0" number)
const FizzBuzzItem = (n) => __('li', {}, [
Boolean(n % 3 && n % 5) && n,
n % 3 === 0 && 'Fizz',
n % 5 === 0 && 'Buzz'
]);
const FizzBuzz = () => __('section', {}, [
__('h1', {}, 'FizzBuzz question'),
__('ul', {}, Array.from(Array(100).keys()).map(FizzBuzzItem))
]);
document.body.appendChild(FizzBuzz());
"used" function
"used" function just executes function with given argument and returns that argument
// used(function, argument)
document.body.appendChild(__('section', {}, [
__('h1', {}, 'Hello button'),
__('p', {}, 'Here is the button that can say hello'),
used(
(button) => button.addEventListener('click', (e) => alert('Hello!')),
__('button', {}, 'Say hello')
)
]));
"appendChildren" function
"appendChildren" function is the same function used in __ to append children. It can be used separately to append children to any element
// appendChildren(parentElement, children)
appendChildren(document.body, [
__('section', {}, 'section 1'),
__('section', {}, 'section 2'),
null,
__('section', {}, 'section 3'),
'non-section text'
]);
Sources
The sources can be found on Github:
And if you love TypeScript as I am, here is the link for you: