0

To dynamically create html (without using a templating library) I have two options. Which of the following is favoured and why?

var cars = [{"id": 1, "name": "volvo"},
            {"id": 2, "name": "nissan"},
            {"id": 3, "name": "audi"}];
for (i = 0; i < cars.length; i++){

    //Option one
    var html = "<li data-id="+cars[i].id+"><a>"+cars[i].name+"</a></li>";
    $('#result-one').append(html);

    //Option two    
    var $el = $('<li/>',{
        'data-id' : cars[i].id
    }).append(
        $('<a/>',{
            text : cars[i].name
        })
    );    
    $('#result-two').append($el);
}

http://jsfiddle.net/joepegler/xk4fumgz/3/

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Joe Austin
  • 557
  • 7
  • 24

3 Answers3

1

For performance this will be the better way :

var cars = [{"id": 1, "name": "volvo"},
            {"id": 2, "name": "nissan"},
            {"id": 3, "name": "audi"}];
var html = "";
for (i = 0; i < cars.length; i++){

   var html += "<li data-id="+cars[i].id+"><a>"+cars[i].name+"</a></li>";

}

$('#result-one').append(html);

This way your appending only one time. The less you append to more performant it is.

http://code.tutsplus.com/tutorials/10-ways-to-instantly-increase-your-jquery-performance--net-5551 Tip #7.

Mathieu Labrie Parent
  • 2,598
  • 1
  • 9
  • 10
  • These two answers both suggest option two is superior to option one, but you suggest otherwise. Why would anyone use option two if it performs worse? http://stackoverflow.com/questions/11173589/best-way-to-create-nested-html-elements-with-jquery http://stackoverflow.com/questions/867916/creating-a-div-element-in-jquery – Joe Austin Dec 15 '14 at 15:36
  • 1
    Because people is concern about code readability rather then performance. I don't think the difference will be that significative, unless you have many element in the DOM and you do intense DOM manipulation. Personnally, i use to the HTML way and it's more readable for me. It's just a question of habits and preference. – Mathieu Labrie Parent Dec 15 '14 at 15:46
1

Despite using a library, lets try not using a library!

var cars = [
        {
            id:1,
            name:'volvo'
        },
        {
            id:2,
            name:'nissan'
        },
        {
            id:3,
            name:'audi'
        }
    ],
    result = document.getElementById('result-two'),
    mainLi = document.createElement('li'),
    mainA = document.createElement('a'),
    setText(function(){
        if('textContent' in document){
            return function(el,text){
                el.textContent = text;
            };
        } else if('innerText' in document){
            return function(el,text){
                el.innerText = text;
            };
        } else {
            return function(el,text){
                el.innerHTML = text;
            };
        }
    })();

for (var i = 0, len = cars.length; i < len; i++){
    var li = mainLi.cloneNode(false),
        a = mainA.cloneNode(false);

    li.setAttribute('data-id',cars[i].id);
    setText(a,cars[i].name);

    li.appendChild(a);    
    result.appendChild(li);
}

And then, if you want to copy and paste:

var copy = result.cloneNode(true);

Which does a deep copy, although you would change the id of the new node. Untested, but what the hell ... it was fun. Should work though, and has the nice benefit of not hand-writing out the elements (as you called out) ... you are creating initial "template" nodes, then cloning them when necessary, then applying appropriate attributes / text. Very clear what is transpiring, and coincidentally very fast. :)

PlantTheIdea
  • 16,061
  • 5
  • 35
  • 40
-1

why not just this:

edit

or even better:

var items = '';
for (i = 0; i < cars.length; i++){
   items += '<li data-id="'+cars[i].id+'"><a>'+cars[i].name+'</a></li>';
}
$('#result-two')[0].innerHTML = items;

this, because it's easier to type and more performant -- it's faster than $('#el').html() and $('#el').append(stuff), as well. jsperf

Community
  • 1
  • 1
Todd
  • 5,314
  • 3
  • 28
  • 45
  • how does this answer the question? It will never produce the html `
  • volvo
  • `. The difficulty was injecting specific info from the array into the HTML and this doesn't even attempt at that. – KyleMit Dec 15 '14 at 15:01
  • @KyleMit so why not this? it is a modified vers of my first. – Todd Dec 15 '14 at 15:19
  • 1
    I'd still say that this answer has a bit to go before it's useful. This just looks pretty much exactly like the solution OP already proposed in option one. The question isn't *how* to do it, but which one is better and *why*. Just providing the how doesn't answer the why. It doesn't provide an argument for why they should choose this answer over any other or what performance benefits there could be of using a method that was already proposed. – KyleMit Dec 15 '14 at 15:32
  • lol. understood first downvote. you're not the guy who downvotes an answer and leaves it, even after the issues have been resolved and is more performant than the accepted answer are you, @KyleMit' – Todd Dec 15 '14 at 15:53