getFirstLevelChildTags (w/tests)
by Tomek
HTML
<script src="http://visionmedia.github.io/mocha/example/mocha.js"></script>
<script src="http://visionmedia.github.io/mocha/example/chai.js"></script>
<link rel="stylesheet" href="http://visionmedia.github.io/mocha/example/mocha.css">
<div id="div-0">
<div id="div-0-0">
<div id="div-0-0-0"></div>
<custom-element id="custom-0-0-0"></custom-element>
</div>
<div id="div-0-1">
<div id="div-0-1-0">
<div id="div-0-1-0-1"></div>
</div>
<div id="div-0-1-1"></div>
<custom-element id="custom-0-1-0">
<custom-element id="custom-0-1-0-0"></custom-element>
</custom-element>
</div>
</div>
<custom-element id="custom-0"></custom-element>
<section id="mocha"></section>
JavaScript
/**
* Returns an array of descendant elements that match the given tag names.
*/
var getFirstLevelChildTags =
function getFirstLevelChildTags(elements) {
var children = [];
elements = Array.prototype.splice.call(elements,0);
elementLoop: for (var i = 0, ilen = elements.length; i < ilen; i++) { // n -times
var elem = elements[i].parentNode;
while ( elem ) { // nth depth times
// is parentNode one of our elements? => elem is not direct child
if ( elements.indexOf( elem )> -1 ) { // n-times
continue elementLoop;
}
elem = elem.parentNode;
}
children.push(elements[i]);
}
return children;
}
mocha.setup('bdd');
expect = chai.expect;
describe('getFirstLevelChildTags', function () {
it('should find one div-child in body', function () {
var children = getFirstLevelChildTags(document.querySelectorAll("div"));
expect(children.length).to.equal(1);
expect(children[0].id).to.equal("div-0");
})
it('should find two (div+custom)-child in body', function () {
var children = getFirstLevelChildTags(document.querySelectorAll("div, CUSTOM-ELEMENT"));
expect(children.length).to.equal(2);
expect(children[1].id).to.equal("custom-0");
expect(children[0].id).to.equal("div-0");
})
it('should find two div-children in div-0-1', function () {
debugger
var children = getFirstLevelChildTags(document.querySelectorAll("#div-0-1 div"));
expect(children.length).to.equal(2);
expect(children[0].id).to.equal("div-0-1-0");
expect(children[1].id).to.equal("div-0-1-1");
})
it('should find three (div+custom)-children in div-0-1', function () {
var children = getFirstLevelChildTags(document.querySelectorAll("#div-0-1 DIV, #div-0-1 CUSTOM-ELEMENT"));
expect(children.length).to.equal(3);
expect(children[2].id).to.equal("custom-0-1-0");
...