diff --git a/src/scripts/lib/foreach-els.js b/src/scripts/lib/foreach-els.js new file mode 100644 index 0000000..7031776 --- /dev/null +++ b/src/scripts/lib/foreach-els.js @@ -0,0 +1,7 @@ +module.exports = function(els, fn, context) { + if (els instanceof HTMLCollection || els instanceof NodeList || els instanceof Array) { + return Array.prototype.forEach.call(els, fn, context) + } + // assume simple dom element + return fn.call(context, els) +} diff --git a/tests/scripts/lib/foreach-els.js b/tests/scripts/lib/foreach-els.js new file mode 100644 index 0000000..2f93aaf --- /dev/null +++ b/tests/scripts/lib/foreach-els.js @@ -0,0 +1,45 @@ +var tape = require("tape") + +var forEachEls = require("../../../src/scripts/lib/foreach-els.js") + +var div = document.createElement("div") +var span = document.createElement("span") +var cb = function(el) { + el.innerHTML = "boom" +} + +tape("test forEachEls on one element", function(t) { + div.innerHTML = "div tag" + forEachEls(div, cb) + + t.equal(div.innerHTML, "boom", "works correctly on one element") + t.end() +}) + + +tape("test forEachEls on an array", function(t) { + div.innerHTML = "div tag" + span.innerHTML = "span tag" + + forEachEls([div, span], cb) + + t.equal(div.innerHTML, "boom", "works correctly on the first element of the array") + t.equal(span.innerHTML, "boom", "works correctly on the last element of the array") + + t.end() +}) + +tape("test forEachEls on an NodeList", function(t) { + div.innerHTML = "div tag" + span.innerHTML = "span tag" + + var frag = document.createDocumentFragment() + frag.appendChild(div) + frag.appendChild(span) + forEachEls(frag.childNodes, cb) + + t.equal(div.innerHTML, "boom", "works correctly on the first element of the document fragment") + t.equal(span.innerHTML, "boom", "works correctly on the last element of the document fragment") + + t.end() +})