Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I'd like to use JavaScript to generate HTML.

I've made a JavaScript function object that has two parameters; a string and generic object. The string is used to specify the type of HTML element you want to generate and the generic object is a container for key value pairs specifying the element's attributes -- or a string for simple elements like paragraphs containing only text that needs no id or class specification.

I'm drafted some functions that generate some HTML elements. I then contained the functions in an array that is a local variable of a function called html.

When html is called with appropriate arguments (e.g. html("element", {id:"myElement"})), a string of HTML text is returned.

I wonder what the drawbacks of the approach are. More specifically, is there a better method to achieve the same results?

var html = function (type, spec={}) {
  html_element = [];

  html_element["table"] = function() {
    markup = "<table>";

    if (spec.cols) 
    {
      markup += "<tr>";

      for (value in spec.cols)
        markup += "<th>" + spec.cols[value] + "</th>";

      markup += "</tr>";
    }

    while (spec.rows.length)
    {
      markup += "<tr>";

      for (data in (row = spec.rows.shift()))
        markup += "<td>" + row[data] + "</td>";

      markup += "</tr>";
    }

    return markup += "</table>";
  };


  html_element["button"] = function() {
    if (spec.hasOwnProperty("value")) value = spec.value;
    else                              value = "";

    return "<button id=\"" + id + "\">" + value + "</button>";
  };


  html_element["p"] = function() {
    if (typeof spec === Object) text = spec.text;
    else                        text = spec;

    return "<p id=\"" + id + "\">" + text + "</p>";
  };

  ...


  return html_element[type]();

}
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.