Skip to content Skip to sidebar Skip to footer

Createtextnode In Javascript Appends Html Content

I am trying to append html formatted block to a existing div using append child. But I see the html code is appending instead of formatted html. Any pointer on how to add html desi

Solution 1:

Why not just use Element.innerHTML? You can use ele.innerHTML = newHtml to overwrite the content, or ele.innerHTML += newHtml to add to the existing content.

var ele = document.getElementById("currentElement");
var newHtml = "<div><h3>hello test continued</h3></div>";
ele.innerHTML += newHtml;
<divid="currentElement"><div><h2>
      Hello test
    </h2></div></div>

Note that this will remove any existing event handlers. In order to retain handlers, you should use Element.insertAdjacentHTML() instead:

var ele = document.getElementById("currentElement");
var newHtml = "<div><h3>hello test continued</h3></div>";
ele.insertAdjacentHTML('beforeend', newHtml);
<divid="currentElement"><div><h2>
      Hello test
    </h2></div></div>

Note that .insertAdjacentHTML() provides the ability to choose where the inserted text should go with one of the following as the (mandatory) first function parameter:

  • 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.

I've gone with beforeend in the above example.

Hope this helps! :)

Solution 2:

If you want do it by appendChild, do it this way :

var newHtml = "<div><h3>hello test continued</h3></div>";
var child = document.createElement('div');
child.innerHTML = newHtml;
child = child.firstChild;
document.getElementById('currentElement').appendChild(child);

https://jsfiddle.net/vdv6yqcL/10/

Solution 3:

If you want to preserve event listeners, you have two options

// sample event listenerdocument.querySelector('#currentElement h2').addEventListener('click', () =>console.log('click works'));
// code starts herevar ele = document.getElementById("currentElement");
var div = document.createElement('div'), 
    h3 = document.createElement('h3'),
    txt = document.createTextNode('hello test continued');
div.appendChild(h3);
h3.appendChild(txt);
ele.appendChild(div);
<divid="currentElement"><div><h2>
    Hello test
    </h2></div></div>

or

// sample event listenerdocument.querySelector('#currentElement h2').addEventListener('click', () =>console.log('click works'));
// code starts herevar ele = document.getElementById("currentElement");
var newHtml = "<div><h3>hello test continued</h3></div>";
ele.insertAdjacentHTML('beforeend', newHtml);
<divid="currentElement"><div><h2>
    Hello test
    </h2></div></div>

Post a Comment for "Createtextnode In Javascript Appends Html Content"