Skip to content

Instantly share code, notes, and snippets.

@yckart
Last active December 17, 2015 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yckart/5652296 to your computer and use it in GitHub Desktop.
Save yckart/5652296 to your computer and use it in GitHub Desktop.
var nthChild = function (elem, num, fn) {
var len = elem.length;
var ret = [];
var i = 0;
// :nth-child(num)
if (!isNaN(Number(num))) {
for (i = 0; i < len; i++) {
if (i === num - 1) {
if (fn) fn(elem[i]);
return elem[i];
}
}
}
// :nth-child(numn+num)
if (num.indexOf('+') > 0) {
var parts = num.match(/\w/g);
for (i = parts[2] - 1; i < len; i += parts[0] | 0) {
if (elem[i]) {
if (fn) fn(elem[i]);
ret.push(elem[i]);
}
}
}
// :nth-child(odd)
if (num === 'odd') {
for (i = 0; i < len; i += 2) {
if (fn) fn(elem[i]);
ret.push(elem[i]);
}
}
// :nth-child(even)
if (num === 'even') {
for (i = 1; i < len; i += 2) {
if (fn) fn(elem[i]);
ret.push(elem[i]);
}
}
return ret;
};
var rows = document.querySelectorAll('li');
var num = nthChild(rows, 2);
num.className += ' num';
var odd = nthChild(rows, 'odd', function (li) {
li.className += 'odd';
});
var even = nthChild(rows, 'even', function (li) {
li.className += ' even';
});
var formula = nthChild(rows, '3n+1', function (li) {
li.className += ' formula';
});
@yckart
Copy link
Author

yckart commented May 26, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment