gelerator
Generate Elements in a simple way.
English | 简体中文
Javascript | Elements |
---|---|
g('div#ID.two.classes')() |
<div id="ID" class="two classes"></div> |
g('button#main')('content') |
<button id="main">content</button> |
g('span', { style: 'color: red' })('RED') |
<span style="color: red">RED</span> |
g('ol')(g('li')(1), g('li')(2)) |
<ol><li>1</li><li>2</li></ol> |
Special | Usages |
g('.default.tagName.is)('DIV') |
<div class="default tagName is">DIV</div> |
g('input#forInputOnly')('VALUE') |
<input id="forInputOnly" value='VALUE'/> |
g('img#forImgOnly')('./demo.jpg') |
<img id="forImgOnly" src="./demo.jpg"> |
generate list by array
const arr = ['a', 'b', 'c', 'd']
// es6
const ctnr = g('ol.ctnr')(
...arr.map((item, idx) => g('li')(item))
)
element template
const P = g('p', { ...some attrs }) // p tag template
const p1 = P('content1')
const p2 = P('content2') // p1 and p2 got the same attributes
specified style attribute
// string is allowed in style attr
const el = g('#styled', {
style: 'top: 1px; left: 1px'
})('content')
// object is also allowed
const el = g('#styled', {
style: {
top: '1px',
left: '1px'
}
})('content')
addEventListener
// attribute start with _ will be treat as an event
const btn = g('button', {
_click: () => alert('hello world')
})('click me')
const btn = g('button', () => alert('hello world'))('click me')
Syntax
g(selector[, attr])(arg1[, arg2[, ...]])
Parameters
selector
Type: String
CSS selector format with tag#id.class1.class2
.
attr
Type: Function
| Object
If Function
were given, it'll be tag's onclick
event.
Otherwise, generate Object
as the tag's attributes.
Especially, object key start with _
would be treat as an event.
For style
key, both string and object are available.
arg1, arg2, ...
Type: String
| Node
if String
were given, it'll be tag's innerText
.
Otherwise, append Node
to the tag.
Especially, given String
will be this IMG
tag's src
attribute.
Especially, given String
will be this INPUT
tag's value
attribute.
Usage
1. install
or yarn add gelerator
2. import gelerator
import { g } from 'gelerator'
3. generate elements
let userMessages = [
'hi',
'what are you up to?',
'<script>alert("something evil")</script>'
]
g('chat-list')(
g('ul')(
...userMessages.map(msg => g('li')(msg)),
g('li.chat-end')('end of line')
)
)
Output:
<div class="chat-list">
<ul>
<li>hi</li>
<li>what are you up to?</li>
<li><script>alert("something evil")</script></li>
<li class="chat-end">end of line</li>
</ul>
</div>
License
MIT
Dev with TodoMVC
- install all the dev dependencies:
yarn
- dev:
yarn dev
- package:
yarn build
Contributing
- Fork this repo
- Create your feature branch:
git checkout -b MY-NEW-FEATURE
- Commit your changes:
git commit -am 'ADD SOME FEATURE'
- Push to the branch:
git push origin MY-NEW-FEATURE
- Submit a pull request :D