Skip to content

Instantly share code, notes, and snippets.

@therealklanni
Forked from prettydiff/getNodesByType
Last active August 29, 2015 13:56
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 therealklanni/8853495 to your computer and use it in GitHub Desktop.
Save therealklanni/8853495 to your computer and use it in GitHub Desktop.
/*global document*/
//a function to get DOM nodes by nodeType property.
//If you do not supply a value I will give you every DOM node.
//
//example:
// var allComments = document.getNodesByType(8);
// or
// var allComments = document.getNodesByType("COMMENT_NODE");
//
//The accepted string values are the actual node type names, so that the
//typeValue argument can be supplied dynamically from other code.
//
//
// Please try http://prettydiff.com/ for all your web development needs!
//
//
//Keep in mind that the following node types are valid in the W3C DOM
//standards, but have been deprecated in the WHATWG DOM specification.
//
// 2 - ATTRIBUTE_NODE
// 4 - CDATA_SECTION_NODE
// 5 - ENTITY_REFERENCE_NODE
// 6 - ENTITY_NODE
// 12 - NOTATION_NODE
//
//This means all node types are still valid in the standard, but the
//deprecated types may not be retrievable from certain DOM
//implementations.
//
;(function(doc) {
doc.getNodesByType = function (typeValue) {
'use strict';
var types = 0,
typeList = {
'ALL': 0,
'ELEMENT_NODE': 1,
'ATTRIBUTE_NODE': 2,
'TEXT_NODE': 3,
'CDATA_SECTION_NODE': 4,
'ENTITY_REFERENCE_NODE': 5,
'ENTITY_NODE': 6,
'PROCESSING_INSTRUCTION_NODE': 7,
'COMMENT_NODE': 8,
'DOCUMENT_NODE': 9,
'DOCUMENT_TYPE_NODE': 10,
'DOCUMENT_FRAGMENT_NODE': 11,
'NOTATION_NODE': 12
};
if (typeValue in typeList) {
types = typeList[typeValue];
} else {
types = parseInt(typeValue, 10);
}
return (function () {
var root = doc.documentElement,
output = [],
child = function (x) {
var a = x.childNodes,
b = a.length,
c = 0;
for (c = 0; c < b; c += 1) {
if (a[c].nodeType === types || types === 0) output.push(a[c]);
if (a[c].nodeType === 1) child(a[c]);
}
};
if (types === 1 || types === 0) output.push(root);
child(root);
return output;
}());
};
}(document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment