Reputation: 6259
I would like to append Html as a child to a Element, i tried:
$.each(data, function(i, field){
var tbody = document.getElementsByTagName('tbody')[0];
tbody.appendChild('<tr><td>'+ field.name +'</td><td>' + field.vorname + '</td><td>' + field.geburtsdatum + '</td><td>' + field.strasse + '</td><td>' + field.plz + '</td></tr>');
});
But somehow i get this error:
Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
How can i fix this problem? Thanks
Upvotes: 0
Views: 2234
Reputation: 388316
appendChild() takes a node as the argument, try jQuery's append() instead
var $tbody = $('tbody').eq(0);
$.each(data, function (i, field) {
$tbody.append('<tr><td>' + field.name + '</td><td>' + field.vorname + '</td><td>' + field.geburtsdatum + '</td><td>' + field.strasse + '</td><td>' + field.plz + '</td></tr>');
});
As Json said, it is best to create the html first then append it, so try
var array = $.map(data, function (field, i) {
return '<tr><td>' + field.name + '</td><td>' + field.vorname + '</td><td>' + field.geburtsdatum + '</td><td>' + field.strasse + '</td><td>' + field.plz + '</td></tr>';
});
$('tbody').eq(0).append(array.join(''));
Upvotes: 3