Skip to content

Instantly share code, notes, and snippets.

@karolk
Last active August 29, 2015 13:57
Show Gist options
  • Save karolk/9842061 to your computer and use it in GitHub Desktop.
Save karolk/9842061 to your computer and use it in GitHub Desktop.
Walks the DOM and records it as a JS object. Very useful for skimwords!
var generateNodeRecorer = function(forEach) {
function parseArgs(nodes, collecionOrNodeCallback, nodeCallback) {
//make sure single objects can be handled
if (!nodes.length) nodes = [nodes];
if (arguments.length === 0) {
throw new Error('Couldn\'t find nodes')
}
if (arguments.length === 1) {
return nodeRecorder(nodes, [])
}
if (arguments.length === 2) {
if (Array.isArray(collecionOrNodeCallback)) {
return nodeRecorder(nodes, collecionOrNodeCallback)
}
else if (typeof collecionOrNodeCallback === 'function') {
return nodeRecorder(nodes, [], collecionOrNodeCallback)
}
else {
throw new Error('Second argument should be an array or a function')
}
}
if (arguments.length >= 3) {
return nodeRecorder(nodes, collecionOrNodeCallback, nodeCallback)
}
}
var nodeRecorder = function(nodes, collection, nodeCallback) {
forEach.call(nodes, function(node) {
var nodeObj = {}
if (node.tagName) {
nodeObj.tag = node.tagName
}
else {
nodeObj.text = node.textContent
}
if (node.childNodes.length) {
nodeObj.children = []
nodeRecorder(node.childNodes, nodeObj.children, nodeCallback)
}
if (nodeCallback) {
nodeCallback(nodeObj, node, collection);
}
collection.push(nodeObj)
})
return collection
}
return parseArgs
}
var nodeRecorder = generateNodeRecorer([].forEach);
//example usage
//nodeRecorder(document.body)
//nodeRecorder(document.querySelectorAll('div'))
//pass function to manipulate node objects and attach/remove properties
//nodeRecorder(document.querySelectorAll('div'), function(nodeObj, node) {nodeObj.node = node})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment