Last active
December 17, 2015 18:19
-
-
Save yckart/5652296 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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'; | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsfiddle.net/ARTsinn/s3KLz/