Есть два способа добавить HTML-код в DOM, и я не знаю, как лучше всего это сделать.
Первый метод
Первый способ самый простой, я мог бы просто добавить HTML-код (с помощью jQuery), используя $('[code here]').appendTo(element);
, что очень похоже на element.innerHTML = [code here];
Второй метод
Другой способ - создать все элементы один за другим, например:
// New div-element
var div = $('<div/>', {
id: 'someID',
class: 'someClassname'
});
// New p-element that appends to the previous div-element
$('<p/>', {
class: 'anotherClassname',
text: 'Some textnode',
}).appendTo(div);
Этот метод использует основные функции, такие как document.createElement
и element.setAttribute
.
Когда я должен использовать первый метод, а когда второй? Является ли метод два быстрее, чем метод один?
Редактировать - Результат скоростных тестов
Я сделал три теста скорости, из которых следует код:
$(document).ready(function(){
// jQuery method - Above mentioned as the second method
$('#test_one').click(function(){
startTimer();
var inhere = $('#inhere');
for(i=0; i<1000; i++){
$(inhere).append($('<p/>', {'class': 'anotherClassname' + i, text: 'number' + i}));
}
endTimer();
return false;
});
// I thought this was much like the jQuery method, but it was not, as mentioned in the comments
$('#test_two').click(function(){
startTimer();
var inhere = document.getElementById('inhere');
for(i=0; i<1000; i++){
var el = document.createElement('p')
el.setAttribute('class', 'anotherClassname' + i);
el.appendChild(document.createTextNode('number' + i));
inhere.appendChild(el);
}
endTimer();
return false;
});
// This is the innerHTML method
$('#test_three').click(function(){
startTimer();
var inhere = document.getElementById('inhere'), el;
for(i=0; i<1000; i++){
el += '<p class="anotherClassname' + i + '">number' + i + '</p>';
}
inhere.innerHTML = el;
endTimer();
return false;
});
});
Что дало следующие действительно удивительные результаты
Test One Test Two Test Three
+-------------+---------+----------+------------+
| Chrome 5 | ~125ms | ~10ms | ~15ms |
| Firefox 3.6 | ~365ms | ~35ms | ~23ms |
| IE 8 | ~828ms | ~125ms | ~15ms |
+-------------+---------+----------+------------+
В целом метод innerHTML кажется самым быстрым и во многих случаях наиболее читаемым.