views:

14

answers:

1

I have a method that is trying to take in a list. This list can contain data and other lists. The end goal is to try to convert something like this

["a", "b", ["c", "d"]]  

into

<ol>
    <li>
        <b>a</b>
    </li>
    <li>
        <b>b</b>
    </li>
    <ol>
        <li>
            <b>c</b>
        </li>
        <li>
            <b>d</b>
        </li>
    </ol>
</ol>

The code is:

function $(tagName) {
    return document.createElement(tagName);
}

//returns an html element representing data
//data should be an array or some sort of value
function tagMaker(data) {
    tag = null;


    if(data instanceof Array) {
        //data is an array, represent using <ol>
        tag = $("ol");
        for(i=0; i<data.length; i++) {
            //construct one <li> for each item in the array 
            listItem = $("li");
            //get the html element representing this particular item in the array
            child = tagMaker(data[i]);
            //<li>*html for child*</li>
            listItem.appendChild(child);
            //add this item to the list
            tag.appendChild(listItem);
        }
    } else {
        //data is not an array, represent using <b>data</b>
        tag = $("b");
        tag.innerHTML = data.toString();
    }

    return tag;
}

Calling tagMaker throws HIERARCHY_REQUEST_ERR: DOM Exception 3, rather than generating a helpful HTML element object which I was planning to append to document.body.

A: 

I figured it out. Within a function if you do not use the var keyword when creating new variables, Javascript will give the variables a global scope. When I was trying to recursively generate new tags, it overwrote the parent tag. The error arises because I was trying to add an element to itself. A working version appears below.

function $(tagName) {
    return document.createElement(tagName);
}

//returns an html element representing data
//data should be an array or some sort of value
function tagMaker(data) {
    var tag = null;


    if(data instanceof Array) {
        //data is an array, represent using <ol>
        tag = $("ol");
        for(var i=0; i<data.length; i++) {
            //construct one <li> for each item in the array 
            var listItem = $("li");
            //get the html element representing this particular item in the array
            var child = tagMaker(data[i]);
            //<li>*html for child*</li>
            listItem.appendChild(child);
            //add this item to the list
            tag.appendChild(listItem);
        }
    } else {
        //data is not an array, represent using <b>data</b>
        tag = $("b");
        tag.innerHTML = data.toString();
    }

    return tag;
}
Mark