156

I am trying to insert a chunk of HTML into a div. I want to see if plain JavaScript way is faster than using jQuery. Unfortunately, I forgot how to do it the 'old' way. :P

var test2 = function(){
    var cb = function(html){
        var t1 = document.getElementById("test2");
        var d = document.createElement("div");
        d.id ="oiio";
        d.innerHtml = html;
        t1.appendChild(d);
        console.timeEnd("load data with javascript");
    };
    console.time("load data with javascript");
    $.get("test1.html", cb);
}

what am i doing wrong here guys?

edit:
Someone asked which is faster, jquery or plain js so i wrote up a test:
https://jsben.ch/FBQYM

plain js is 10% faster

EscapeNetscape
  • 2,892
  • 1
  • 33
  • 32
mkoryak
  • 57,086
  • 61
  • 201
  • 257

6 Answers6

233

I think this is what you want:

document.getElementById('tag-id').innerHTML = '<ol><li>html data</li></ol>';

Keep in mind that innerHTML is not accessible for all types of tags when using IE. (table elements for example)

danronmoon
  • 3,814
  • 5
  • 34
  • 56
Nathan
  • 11,938
  • 12
  • 55
  • 62
  • 33
    +1 for mentioning the IE compatibility, wish everyone did this! – Enrico Aug 01 '13 at 12:39
  • 2
    Is there any alternate solution to insert a big HTML code? if we use the above method we should write multiple lines of HTML code in between the quotes which will not look professional. – Praveen Kumar Jul 30 '21 at 19:19
  • @PraveenKumar add a + to Nathan's code, like document.getElementById('tag-id').innerHTML += '
    1. html data
    '; in this way u added HTML code without delete the parents HTML (inner)
    – MaZzIMo24 Dec 02 '22 at 08:58
57

Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:

$('#yourDivName').html('yourtHTML');

You may also consider using:

$('#yourDivName').append('yourtHTML');

This will add your gallery as the last item in the selected div. Or:

$('#yourDivName').prepend('yourtHTML');

This will add it as the first item in the selected div.

See the JQuery docs for these functions:

Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
designerdre101
  • 795
  • 1
  • 6
  • 7
  • 29
    OP specifically asked for plain javascript, but this helped me, so I still consider it useful. – doubleJ Jul 18 '12 at 18:05
  • Would help to see an example with a long string of Html inserted. For example, I have a case in which server technologies (php etc) are disallowed, and I want to re-use about 20 lines of html inside the same page. – Jen Jan 30 '14 at 04:47
  • This could come in handy. Thanks. – arunken May 11 '19 at 07:37
52

I using "+" (plus) to insert div to html :

document.getElementById('idParent').innerHTML += '<div id="idChild"> content html </div>';

Hope this help.

Yosep Tito
  • 737
  • 6
  • 7
36

As alternative you can use insertAdjacentHTML - however I dig into and make some performance tests - (2019.09.13 Friday) MacOs High Sierra 10.13.6 on Chrome 76.0.3809 (64-bit), Safari 12.1.2 (13604.5.6), Firefox 69.0.0 (64-bit) ). The test F is only for reference - it is out of the question scope because we need to insert dynamically html - but in F I do it by 'hand' (in static way) - theoretically (as far I know) this should be the fastest way to insert new html elements.

enter image description here

SUMMARY

  • The A innerHTML = (do not confuse with +=) is fastest (Safari 48k operations per second, Firefox 43k op/sec, Chrome 23k op/sec) The A is ~31% slower than ideal solution F only chrome but on safari and firefox is faster (!)
  • The B innerHTML +=... is slowest on all browsers (Chrome 95 op/sec, Firefox 88 op/sec, Sfari 84 op/sec)
  • The D jQuery is second slow on all browsers (Safari 14 op/sec, Firefox 11k op/sec, Chrome 7k op/sec)
  • The reference solution F (theoretically fastest) is not fastest on firefox and safari (!!!) - which is surprising
  • The fastest browser was Safari

More info about why innerHTML = is much faster than innerHTML += is here. You can perform test on your machine/browser HERE

let html = "<div class='box'>Hello <span class='msg'>World</span> !!!</div>"

function A() {    
  container.innerHTML = `<div id="A_oiio">A: ${html}</div>`;
}

function B() {    
  container.innerHTML += `<div id="B_oiio">B: ${html}</div>`;
}

function C() {    
  container.insertAdjacentHTML('beforeend', `<div id="C_oiio">C: ${html}</div>`);
}

function D() {    
  $('#container').append(`<div id="D_oiio">D: ${html}</div>`);
}

function E() {
  let d = document.createElement("div");
  d.innerHTML = `E: ${html}`;
  d.id = 'E_oiio';
  container.appendChild(d);
}

function F() {    
  let dm = document.createElement("div");
  dm.id = "F_oiio";
  dm.appendChild(document.createTextNode("F: "));

  let d = document.createElement("div");
  d.classList.add('box');
  d.appendChild(document.createTextNode("Hello "));
  
  let s = document.createElement("span");
  s.classList.add('msg');
  s.appendChild(document.createTextNode("World"));

  d.appendChild(s);
  d.appendChild(document.createTextNode(" !!!"));
  dm.appendChild( d );
  
  container.appendChild(dm);
}


A();
B();
C();
D();
E();
F();
.warr { color: red } .msg { color: blue } .box {display: inline}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="warr">This snippet only for show code used in test (in jsperf.com) - it not perform test itself. </div>
<div id="container"></div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • Strange, I have heard that innerHTML should be MUCH slower than insertAdjacentHTML, usualy by several orders of magnitude, becasue innerHTML parses the whole document and does wierd string stuff to it, and insertAdjacentHTML just inserts it where it is needed. Not ture why it is the oposite here now? Maybe some performance update or something? – Sebastian Norr Jul 07 '21 at 17:10
  • From my personal experience I can say insertAdjacentHTML was way faster thank innerHTML – math Apr 15 '22 at 14:30
20
document.getElementById('tag-id').insertAdjacentHTML("beforebegin",'<ol><li>html data</li></ol>')

'beforebegin': Before the element itself
'afterbegin': Just inside the element, before its first child
'beforeend': Just inside the element, after its last child
'afterend': After the element itself

More details : developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

ZygD
  • 22,092
  • 39
  • 79
  • 102
Majid Gabrlo
  • 659
  • 6
  • 5
18

And many lines may look like this. The html here is sample only.

var div = document.createElement("div");

div.innerHTML =
    '<div class="slideshow-container">\n' +
    '<div class="mySlides fade">\n' +
    '<div class="numbertext">1 / 3</div>\n' +
    '<img src="image1.jpg" style="width:100%">\n' +
    '<div class="text">Caption Text</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">2 / 3</div>\n' +
    '<img src="image2.jpg" style="width:100%">\n' +
    '<div class="text">Caption Two</div>\n' +
    '</div>\n' +

    '<div class="mySlides fade">\n' +
    '<div class="numbertext">3 / 3</div>\n' +
    '<img src="image3.jpg" style="width:100%">\n' +
    '<div class="text">Caption Three</div>\n' +
    '</div>\n' +

    '<a class="prev" onclick="plusSlides(-1)">&#10094;</a>\n' +
    '<a class="next" onclick="plusSlides(1)">&#10095;</a>\n' +
    '</div>\n' +
    '<br>\n' +

    '<div style="text-align:center">\n' +
    '<span class="dot" onclick="currentSlide(1)"></span> \n' +
    '<span class="dot" onclick="currentSlide(2)"></span> \n' +
    '<span class="dot" onclick="currentSlide(3)"></span> \n' +
    '</div>\n';

document.body.appendChild(div);
atom
  • 692
  • 7
  • 11