0.1.4 • Published 8 years ago
dom-splicer v0.1.4
dom-splicer
A minimalist, performance oriented, splicer able to mutate an element's childNodes directly, or indirectly.
Alternative
If you need to diff without direct .splice calls, check domdiff out.
Configuration
The class constructor accepts an object with these properties:
target, the target element, or its wrap, to mutate on splice calls. If omitted, thebefore.parentNodewill be used instead.childNodes, optionalArrayof zero, one, or more nodes (already childNodes of the target). It is possible to use this Array as facade for a range of elements. If omitted, andtargetis specified, but not thebeforenode, itschildNodeswill be used instead.item, optionalFunctioninvoked per each item that is being removed or inserted. If the givenchildNodescontains nodes wraps, you can return their real content once theitem(wrap)is invoked. Used to understandtargetand/orbeforetoo.before, optionalNodeto use as anchor for the range ofchildNodesto modify. If specified, andtargetis not, itsparentNodewill be used per each splice. This is handy when a node to use as anchor is created inside a fragment but moved, or appended, later on.
Examples
Basic DOM manipulation.
const mutator = new DOMSplicer({
target: document.body
});
// unshift a, b
mutator.splice(
0, 0,
document.createTextNode('a'),
document.createTextNode('b')
);
// push c, d
mutator.splice(
mutator.childNodes.length, 0,
document.createTextNode('d'),
document.createTextNode('e')
);
// insert at index
mutator.splice(
2, 0,
document.createTextNode('c')
);Using a range of node wraps.
// demo purpose, two nodes on the body, a placeholder in between
document.body.innerHTML = '<b>1</b><!--ph--><b>5</b>';
// a generic node wrap
class Wrap {
constructor(value) {
this._node = document.createElement('b');
this._node.textContent = value;
}
unwrap() {
return this._node;
}
}
// a splicer used as inner range
const range = new DOMSplicer({
target: document.body,
childNodes: [],
item: wrap => wrap.unwrap(),
before: document.body.childNodes[1]
});
// unshift/push 2 nodes
range.splice(
0, 0,
new Wrap(2), new Wrap(4)
);
// insert a node in beteen
range.splice(
1, 0,
new Wrap(3)
);
// verify the content
document.body.innerHTML;
// <b>1</b><b>2</b><b>3</b><b>4</b><!--ph--><b>5</b>
// revert all nodes
range.splice(
0, range.childNodes.length,
range.childNodes[2],
range.childNodes[1],
range.childNodes[0]
);
// verify the content
document.body.innerHTML;
// <b>1</b><b>4</b><b>3</b><b>2</b><!--ph--><b>5</b>
// drop all nodes
range.splice(0);
// verify the content
document.body.innerHTML;
// <b>1</b><!--ph--><b>5</b>