Skip to main content

Ivan Teoh

Something personal yet public

172-homework3.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;
}

// total is not include the newly elements
var total = getTextNode().length;
var child = document.createTextNode(total);
var parent = document.createElement('span');
parent.setAttribute('id','special_span');
parent.appendChild(child);
document.getElementsByTagName('body')[0].lastChild.appendChild(parent);

var bold = document.createTextNode('bold');
var link = document.createElement('a');
link.setAttribute('href','#');
link.setAttribute('onclick',
'document.getElementById("special_span").innerHTML="<strong>"' +
'+document.getElementById("special_span").innerHTML+"</strong>"');
link.appendChild(bold);
document.getElementsByTagName('body')[0].appendChild(link);