Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it wrong to use jquery to output html tags?

Tags:

jquery

Just wondered is it bad practice to output html tags with javascript. For example say I had a table and on the page load an ajax request gets the data to populate it. For each row of data I'm going to need to output another row, something like this:

$('#results').html('<tr><td>'+data.people[i]['name']+'</td><td>'+data.people[i]['age']+'</td><td>'+data.people[i]['gender']+'</td></tr>');

Is it bad to do this?

like image 932
geoffs3310 Avatar asked Jan 24 '11 13:01

geoffs3310


3 Answers

No this is normal practice. This is how you would normally add html dynamically on the fly.

like image 106
sushil bharwani Avatar answered Oct 18 '22 20:10

sushil bharwani


its not bad. There are two things you could do to imrove it:

I suppose you have this in a each loop, so you could construct your full table before setting it with HTML. So you do the .html() operation just once.

var yourTableHTML = ""

$.each(yourContentArray, function(data,i){
  youtTableHTML += '<tr><td>'+data.people[i]['name']+'</td><td>'+data.people[i]['age']+'</td><td>'+data.people[i]['gender']+'</td></tr>'
})

$('#results').html(yourTableHTML);

The second thing is, that you could use a HTML model inside you HTML file (a model row) that you clone. So if anyone else has to change the HTML once, he does not need to change the javascript to.

like image 3
meo Avatar answered Oct 18 '22 21:10

meo


It's ok only if this JS is in an external file.

Else, IE can drive you crazy and your HTML won't validate if in XHTML and strict.

like image 2
Shikiryu Avatar answered Oct 18 '22 22:10

Shikiryu