Ajey
Ajey

Reputation: 8202

Generating HTML via javascript/jquery. Good programming practice?

Is it good practice to generate HTML through Javascript/Jquery like this:

$('<input></input>', {
      'id': this.elements.verticalPanel.layout2,
      'type': 'button',
      'value': '2',
      'data-toggle': 'tooltip',
      /*'title': 'Layout 2',*/
      'class': this.elements.verticalPanel.panelElement
    })
      .tooltip()
      .appendTo(div);

This is just a small snippet from my code.

Well the functionality works just fine, but I was curious as to know whether other developers follow this practice ?

Upvotes: 2

Views: 109

Answers (4)

Geuis
Geuis

Reputation: 42277

Like that is fine in small doses. If you are in a situation where you need to generate a lot of html, there's a much better way to do it.

Basically, build up your html as a string. Then create an in-memory element and set its innerHTML to your string. You can then append the element to somewhere in the DOM, or operate on its child elements (your html) and do whatever needs doing.

Here's a simple, quickly hacked together sample: http://jsfiddle.net/ygL7f/

var sample = ['<ul>'],
    els = 1000;

for(var i=1; i<els; i++){
    sample[i] = '<li>'+ (Math.random() * 10) +'</li>'
}

sample.push('</ul>');

var root = document.createElement('div');
root.innerHTML = sample.join('');

document.querySelector('body').appendChild(root);

The critical thing to remember when generating lots of html this way is to avoid function calls wherever possible. Function calls are expensive.

In my sample, notice how I'm assigning the html directly to the array index instead of calling sample.push('string'). Faster this way.

Upvotes: 2

Barmar
Barmar

Reputation: 781096

If you need to generate DOM elements dynamically, the alternative to this would be a long sequence of string concatenations. I find this jQuery style far more readable, and I generally use it.

Upvotes: 0

user1721049
user1721049

Reputation:

I am a web developer for many years. we use this method only for generating dynamic updated html and few html code. sometimes it is difficult to navigate correctly through this newly generated dom . the disadvantage of this method is that user can't load those html if javascript is blocked by the user browser

Upvotes: 1

robnick
robnick

Reputation: 1768

JQuery can be used to manipulate, and generate, HTML. Good practice would also mean you clearly comment your code and refactor it to simple re-usable components. What you are doing isn't "wrong".

Upvotes: 0

Related Questions