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?
No this is normal practice. This is how you would normally add html dynamically on the fly.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With