OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Best way to create large static DOM elements in JavaScript?

  • Thread starter Thread starter Tony R
  • Start date Start date
T

Tony R

Guest
I have many elements that one of my JS widgets needs to create and add to the DOM often. They never change.

So one option would be to store the HTML itself as a string in JS and use JQuery to create the elements from the string, then append it to the document:

Code:
var elements = "<div><table><tr><td>1</td><td>2</td></tr></table></div>";
function create() {
  return $(elements);
}
$("body").append(create());

Another option is to write a function that will use document.createElement("div"), or $("<div>") many times to build the elements, append them to each other where needed, then append to the document:

Code:
function create() {
  return $("<div>").append($("<table>")......
}
$("body").append(create());

In the first case, I have a big JS string that is actually HTML. In the second case, I have an unwieldy piece of JS that actually represents HTML.

Are there (dis)advantages to one or the other? Is there a better solution I'm not thinking of?

<p>I have many elements that one of my JS widgets needs to create and add to the DOM often. They never change.</p>

<p>So one option would be to store the HTML itself as a string in JS and use JQuery to create the elements from the string, then append it to the document: </p>

<pre><code>var elements = "<div><table><tr><td>1</td><td>2</td></tr></table></div>";
function create() {
return $(elements);
}
$("body").append(create());
</code></pre>

<p>Another option is to write a function that will use document.createElement("div"), or $("<div>") many times to build the elements, append them to each other where needed, then append to the document:</p>

<pre><code>function create() {
return $("<div>").append($("<table>")......
}
$("body").append(create());
</code></pre>

<p>In the first case, I have a big JS string that is actually HTML. In the second case, I have an unwieldy piece of JS that actually represents HTML.</p>

<p>Are there (dis)advantages to one or the other? Is there a better solution I'm not thinking of?</p>
 

Latest posts

Top