Skip to main content

Ivan Teoh

Something personal yet public

172-homework1.js

(Source)

// from Douglas Crockford's video 'An Incovenient API - The Theory of the DOM'
// http://video.yahoo.com/watch/111582/992708
function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
}

function getTextNode() {
    var result = [];
    // http://forums.htmlhelp.com/index.php?showtopic=5173
    var someElementRef = document.getElementsByTagName('body')[0];
    // remove all the spaces and new lines
    someElementRef.innerHTML = someElementRef.innerHTML.replace(
      /\B\s\B|[\n\r\t]/g, '');
    walkTheDOM(someElementRef, function(node) {
        var nodeName = node.nodeName;
        if (nodeName === '#text') {
            result.push(node);
        }
    });
    return result;
}

alert(getTextNode().length);