Created
October 24, 2016 19:56
-
-
Save tuespetre/f91b91bfd4dabab04e57a6db187c0c34 to your computer and use it in GitHub Desktop.
A polyfill for the ParentNode interface
This file contains 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
(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); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much 😽
Oh, PhpStorm is nagging about some unused variables 😱 The variable
length
should be used in the for loop inchildElementCount
andchildren
(or not at all) 😉