underdom
Underdom is a minimalist helper library to make writing vanilla javascript DOM manipulation just a bit easier with some chaining while still making it completely compatible with the vanilla DOM API.
Why ?
Sprinkle in the convenience of chaining common DOM methods in 855 bytes
Before (one element)
var el = document;elstyledisplay = 'inline-block';elstylepadding = '10px';elclassName = 'blocky';el;eldocumentbody;
After
var el = document;
Before (multiple elements)
var el1 = document;for var i=0; i<10; i++var subel = document;subelstyledisplay = 'inline-block';subelstylepadding = '10px';subelstylewidth = '33%';subeltextContent = 'Box ' + i+1;el1;slice
After (multiple elements)
var el1 = document;for var i=0; i<10; i++// no variable createddocument;el1
Where it shines!
check this out!
underdom really shines when you are creating a lot of elements and trying to do things with them --documentbodyfori =0; i< 10; i++document
Methods
Each of these methods returns the DOM node so they can be chained
name | arguments | description | example |
---|---|---|---|
css | css | sets the style properties of the node(s) using an object with each style property as the key, similar to jquery but only supports objects | document.querySelectorAll('span')._css({background: 'red', 'font-size': '12px'}) |
attr | attr | sets the attribute properties of the node(s) using an object with each attribute name as the key, similar to jquery but only supports objects | document.getElementsByTagName('input')._css({checked: true, 'data-color': 'blue'}) |
text | text | sets the .textContent of the node(s) | document.getElementsByClassName('items')._text('Hello') |
html | html | sets the .innerHTML of the node(s) | document.querySelectorAll('div[data-color="blue"]')._html('<span>hi</span>') |
appendTo | target | appends the element to the target DOM node(s) | document.createElement('div')._html('<span>hi</span>')._appendTo(document.body) |
append | child | appends child to the node(s) | document.body._append(document.createElement('div')._text('hello')) |
on | ev, fn | does document.addEventLisenter(ev, fn) to the node(s) | document.getElementsByTagName('input')._on('change', function(e){ console.log('checked', e.target.checked); }) |
How to use this?
Option 1. paste the minified code into your project
Nodeprototype{return tthis}Nodeprototype{return thisthis}Nodeprototype{return thistextContent=t||""this}Nodeprototype{return thisinnerHTML=t||""this}Nodeprototype{forvar o in tthisstyle;return this}Nodeprototype{forvar o in tto||0===to?"boolean"==typeof to?thiso=to:this:this;return this}Nodeprototype{return thisthis}NodeListprototype__proto__=Arrayprototype;var methods="css""attr""appendTo""append""text""html";methods;
Option 2. RawGit
Option 3: ???
I don't ever use front-end bundlers so I need to be educated
License
MIT