2
\$\begingroup\$

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]();

}
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

Normally, is a good practice create sub functions instead of add all on an array.

var button = function() {

};

Always use var in front of the variables to scope to the context. (good practice).

A good choice is take advantage of the evaluation of data types on javascript, for variables.

var variable = paramValue || "defaultValue";

this evaluates paramaValue, if is true, is assigned, if not, assign "defaultValue"

Also, if is possible, considere use a template engine like:

Final Code

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.