Skip to content

Instantly share code, notes, and snippets.

@tuespetre
Created October 24, 2016 19:56
Show Gist options
  • Save tuespetre/f91b91bfd4dabab04e57a6db187c0c34 to your computer and use it in GitHub Desktop.
Save tuespetre/f91b91bfd4dabab04e57a6db187c0c34 to your computer and use it in GitHub Desktop.
A polyfill for the ParentNode interface
(function() {
var polyfill = function(prototype)
{
if (!('firstElementChild' in prototype)) {
Object.defineProperty(prototype, 'firstElementChild', {
get: function() {
var nodes = this.childNodes;
var length = nodes.length;
var current;
for (var i = 0; i < length; i++) {
current = nodes[i];
if (current.nodeType === 1) {
return current;
}
}
return null;
}
});
}
if (!('lastElementChild' in prototype)) {
Object.defineProperty(prototype, 'lastElementChild', {
get: function() {
var nodes = this.childNodes;
var length = nodes.length;
var current;
for (var i = length - 1; i > 0; i--) {
current = nodes[i];
if (current.nodeType === 1) {
return current;
}
}
return null;
}
});
}
if (!('childElementCount' in prototype)) {
Object.defineProperty(prototype, 'childElementCount', {
get: function() {
var nodes = this.childNodes;
var length = nodes.length;
var count = 0;
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].nodeType === 1) {
count++;
}
}
return count;
}
});
}
if (!('children' in prototype)) {
Object.defineProperty(prototype, 'children', {
get: function() {
var nodes = this.childNodes;
var length = nodes.length;
var children = [];
var current;
for (var i = 0; i < nodes.length; i++) {
current = nodes[i];
if (current.nodeType === 1) {
children.push(current);
}
}
return children;
}
});
}
}
polyfill(Element.prototype);
polyfill(Document.prototype);
polyfill(DocumentFragment.prototype);
})();
@robertpainsi
Copy link

robertpainsi commented Apr 21, 2017

Thank you very much 😽

Oh, PhpStorm is nagging about some unused variables 😱 The variable length should be used in the for loop in childElementCount and children (or not at all) 😉

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