jquery.elemental
v1.1.0
Published
Jquery element creator
Downloads
1
Readme
jQuery.Elemental!
A javascript utility for easy and pretty creation of DOM elements using CSS syntax.
Usage
import elemental from 'Elemental'
const $divElement = elemental('div.class-one.class-two#myId');
// '<div class="class-one class-two" id="myId"><div>
const $list = elemental('ul#theList.list-unstyled')
.append([
elemental('li#one')
.text('Item one')
.css('background-color', 'blue'),
elemental('li#two.red')
.html(elemental('img', {
src: '//path/to/my/image'
}),
elemental('li#three', {
style: 'background-color: green;',
})
.text('Item three'),
]);
// <ul class="list-unstyled" id="theList">
// <li id="one" style="background-color: blue;">
// Item one
// </li>
// <li class="red" id="two">
// <img src="//path/to/my/image"/>
// </li>
// <li id="three" style="background-color: green;">
// Item three
// </li>
// </ul>
const $dataSpan = elemental('span', {}, {
foo: 'bar'
});
console.log($dataSpan.data('foo'));
// 'bar'
Methods
constructor ( string string = 'div', object attr = {}, object data = {} ) jQuery Parses a given string and returns a jQuery object containing the element
string
: The string to be parsed. This should be in the formattagName.class.class.class#id
.tagName
must be first,class(es)
andid
can be in any order.tagName
defaults todiv
,class
andid
default to null.attr
: An object containing attributes that will be attached to the element. Note that if an ID is supplied in both thestring
and theattr
, thestring
ID will be used.data
: An object to be passed to the element'sdataset
.
Notes
- Classes and ID specified in the
string
argument are limited to alphanumeric characters and hyphens i.e they should match/[\w-]+/
. If you want to have more complex characters you can pass them as properties in theattr
object. - For convenience, The default export is a factory function that returns a new instance of the
Elemental
object. If you want to access the class itself you canimport { Elemental } from 'jquery.elemental'
. - Although the examples above use
elemental
as the function name, you can call it whatever you wish - I find$$
works nicely:import $$ from 'jquery.elemental'; const myDiv = $$('div#myDiv);
. - This package is designed to be used with webpack and babel. The
main
entry in package json points to the ES6 module in/src
. If this causes problems with your build process you can find the transpiled and bundled code in the/dist
folder.