1

I have a problem when appending new element with JavaScript. I don't use any library such as jQuery or anything else, i'm using native JavaScript while doing this.

Okay, i'm trying to append a new element to the <body> tag. If in jQuery you can use the .append() function, but when using native JavaScript you must use .innerHTML.

Here's my HTML code

<button id="add">
Add
</button>

Here's my JavaScript code

document.getElementById("add").addEventListener("click", (e) => {
  document.getElementsByTagName("body")[0].innerHTML += '<p>Hello world</p>';
});

When i click the 'add' button it's works the first time. But, when i click again it doesn't work. When i try to use jQuery to append new element then it works, is there any less?

nauval
  • 169
  • 1
  • 4
  • 13
  • 4
    *but when using native JavaScript you must use `innerHTML`* Where did you learn that? –  Oct 20 '17 at 19:04
  • Possible duplicate of [Is it possible to append to innerHTML without destroying descendants' event listeners?](https://stackoverflow.com/questions/595808/is-it-possible-to-append-to-innerhtml-without-destroying-descendants-event-list) – Sebastian Simon Oct 20 '17 at 19:08
  • 1
    fun fact: jquery is not using innerHTML for this – GottZ Oct 20 '17 at 19:28
  • @torazaburo I learned it myself, so what should I use? – nauval Oct 21 '17 at 04:31
  • I think I have the wrong thinking about appending in JavaScript :D – nauval Oct 21 '17 at 04:32

3 Answers3

9

You're replacing the entire contents of your body with all new contents, wiping out any elements and any events attached to them.

Don't overwrite .innerHTML. Use .appendChild():

document.getElementById('add').addEventListener('click', function() {
    var p = document.createElement('p');
    p.textContent = 'Hello world';

    document.body.appendChild(p);
});
<button id="add">Add</button>
JLRishe
  • 99,490
  • 19
  • 131
  • 169
1

Or, if you're going to be appending more than one item, create a document fragment, do all your preliminary work on that, then append that to the DOM. The advantage of this method is that the DOM will only be redrawn once. Example:

var frag = document.createDocumentFragment();

var topSquare = document.createElement('div');
frag.appendChild(topSquare);

var rightSquare = document.createElement('div');
frag.appendChild(rightSquare);

document.getElementsByTagName('body')[0].appendChild(frag);

Or, if you absolutely have to use an HTML string for some reason, use this method:

var htmlString = '<p>Hello world</p>';
var para = document.createRange().createContextualFragment(htmlString);
document.getElementsByTagName('body')[0].appendChild(para);
Tom
  • 1,447
  • 1
  • 12
  • 26
0

Try this

   
document.getElementById("add").addEventListener("click", (e) => {
 
 document.getElementById("k").innerHTML += '<p>Hello world</p>';

});
<button id="add">
Add
</button>
<div id= "k"></div>
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34