KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
There are two methods to add HTML-code to the DOM and I don't know what is the best way to do it. First method The first way is the easy one, I could simply add HTML-code (with jQuery) using $('[code here]').appendTo(element); which is much like element.innerHTML = [code here]; Second method Another way is to create all the elements one by one like: // 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); This method uses core functions like document.createElement and element.setAttribute . When should I use the first method and when the second? Is method two faster than method one? Edit - Result of speed tests I did three speed tests from which the code follows: $(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)); i
Tags (comma-separated)
Save Edits
Cancel