Chapter 6 Exercise Set 1

  1. Write a function asHTML which, when given a DOM node, produces a string representing the HTML text for that node and its children. You may ignore attributes, just show nodes as <nodename>. The escapeHTML function from Regular Expressions is available to properly escape the content of text nodes.

    Hint: Recursion!

    function asHTML(node) {
        if (isTextNode(node))
            return escapeHTML(node.nodeValue);
        else if (node.childNodes.length == 0)
            return "<" + node.nodeName + "/>";
        else
            return "<" + node.nodeName + ">" +
                    map(asHTML, node.childNodes).join("") +
                    "</" + node.nodeName + ">";
    }
    
    alert(asHTML(document.body));
    
  2. Write the convenient function removeElement which removes the DOM node it is given as an argument from its parent node.

    function removeElement(node) {
        if (node.parentNode)
            node.parentNode.removeChild(node);
    }
    
    removeElement(newParagraph);
    
  3. The function makeTable takes two arrays as arguments. The first contains the JavaScript objects that it should summarise, and the second contains strings, which name the columns of the table and the properties of the objects that should be shown in these columns. For example, the following will produce the table above:

    makeTable([{Tree: "Apple", Flowers: "White"},
               {Tree: "Coral", Flowers: "Red"},
               {Tree: "Pine",  Flowers: "None"}],
              ["Tree", "Flowers"]);
    

    Write this function.

    function makeTable(data, columns) {
        var headRow = dom("TR");
        forEach(columns, function(name) {
            headRow.appendChild(dom("TH", null, name));
        });
    
        var body = dom("TBODY", null, headRow);
        forEach(data, function(object) {
            var row = dom("TR");
            forEach(columns, function(name) {
                row.appendChild(dom("TD", null, String(object[name])));
            });
            body.appendChild(row);
        });
    
        return dom("TABLE", null, body);
    }
    
    var table = makeTable(document.body.childNodes,
                          ["nodeType", "tagName"]);
    document.body.appendChild(table);
    

    Do not forget to convert the values from the objects to strings before adding them to the table ― our dom function only understands strings and DOM nodes.