Skip to content

Instantly share code, notes, and snippets.

@jeffreybarke
Forked from Zirak/a.js
Created February 24, 2012 02:16
Show Gist options
  • Save jeffreybarke/1896721 to your computer and use it in GitHub Desktop.
Save jeffreybarke/1896721 to your computer and use it in GitHub Desktop.
ol reverse attribute polyfill
//use this if you want support for browsers which don't have ES5 goodies
if (!('reversed' in document.createElement('ol'))) {
(function () {
var lists = document.getElementsByTagName('ol'),
i = 0,
len = lists.length,
reverseList = function (list) {
var children = [],
childNodes = list.childNodes,
count = list.getAttribute('start'),
i,
len,
val;
for (i = 0, len = childNodes.length; i < len; i++) {
// Node.ELEMENT_NODE === 1
if (childNodes[i].nodeType === 1) {
children.push(childNodes[i]);
}
}
//check to see if a start attribute is provided
if (count !== null) {
count = Number(count);
if (isNaN(count)) {
count = null;
}
}
//no, this isn't duplication - start will be set to null
// in the previous if statement if an invalid start attribute
// is provided
if (count === null) {
count = children.length;
}
for (i = 0, len = children.length; i < len; i++) {
val = children[i].getAttribute('value');
if (val !== null && !isNaN(Number(val))) {
count = val;
}
children[i].value = count--;
}
};
for (i; i < len; i++) {
if (lists[i].getAttribute('reversed') !== null) {
reverseList(lists[i]);
}
}
}());
}
//a polyfill for the ordered-list reversed attribute
// http://www.whatwg.org/specs/web-apps/current-work/multipage/grouping-content.html#the-ol-element
// http://www.whatwg.org/specs/web-apps/current-work/multipage/grouping-content.html#dom-li-value
//uses these awesomeness:
// Array.prototype.forEach
// Element.prototype.children
//if you want support for older browsers *cough*IE8-*cough*, then use the other
// file provided
(function () {
'use strict';
if ('reversed' in document.createElement('ol')) {
return;
}
function reverseList(list) {
var children = list.children,
count = list.getAttribute('start'),
val;
// Check to see if a start attribute is provided
if (count !== null) {
count = Number(count);
if (isNaN(count)) {
count = null;
}
}
//no, this isn't duplication - start will be set to null
// in the previous if statement if an invalid start attribute
// is provided
if (count === null) {
count = children.length;
}
[].forEach.call(children, function (child) {
val = child.getAttribute('value');
if (val !== null && !isNaN(Number(val))) {
count = val;
}
child.value = count--;
});
}
[].forEach.call(document.getElementsByTagName('ol'), function (list) {
if (list.getAttribute('reversed') !== null) {
reverseList(list);
}
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment