[javascript] Javascript - Append HTML to container element without innerHTML

I need a way to append HTML to a container element without using innerHTML. The reason why I do not want to use innerHTML is because when it is use like this:

element.innerHTML += htmldata

It works by replacing all of the html first before adding the old html plus the new html. This is not good because it resets dynamic media such as embedded flash videos...

I could do it this way which works:

var e = document.createElement('span');
e.innerHTML = htmldata;
element.appendChild(e);

However the problem with that way is that there is that extra span tag in the document now which I do not want.

How can this be done then? Thanks!

This question is related to javascript html innerhtml

The answer is


I am surprised that none of the answers mentioned the insertAdjacentHTML() method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.

Basic usage:

var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');

alnafie has a great answer for this question. I wanted to give an example of his code for reference:

_x000D_
_x000D_
var childNumber = 3;_x000D_
_x000D_
function addChild() {_x000D_
  var parent = document.getElementById('i-want-more-children');_x000D_
  var newChild = '<p>Child ' + childNumber + '</p>';_x000D_
  parent.insertAdjacentHTML('beforeend', newChild);_x000D_
  childNumber++;_x000D_
}
_x000D_
body {_x000D_
  text-align: center;_x000D_
}_x000D_
button {_x000D_
  background: rgba(7, 99, 53, .1);_x000D_
  border: 3px solid rgba(7, 99, 53, 1);_x000D_
  border-radius: 5px;_x000D_
  color: rgba(7, 99, 53, 1);_x000D_
  cursor: pointer;_x000D_
  line-height: 40px;_x000D_
  font-size: 30px;_x000D_
  outline: none;_x000D_
  padding: 0 20px;_x000D_
  transition: all .3s;_x000D_
}_x000D_
button:hover {_x000D_
  background: rgba(7, 99, 53, 1);_x000D_
  color: rgba(255,255,255,1);_x000D_
}_x000D_
p {_x000D_
  font-size: 20px;_x000D_
  font-weight: bold;_x000D_
}
_x000D_
<button type="button" onclick="addChild()">Append Child</button>_x000D_
<div id="i-want-more-children">_x000D_
  <p>Child 1</p>_x000D_
  <p>Child 2</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hopefully this is helpful to others.


How to fish and while using strict code. There are two prerequisite functions needed at the bottom of this post.

xml_add('before', id_('element_after'), '<span xmlns="http://www.w3.org/1999/xhtml">Some text.</span>');

xml_add('after', id_('element_before'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');

xml_add('inside', id_('element_parent'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');

Add multiple elements (namespace only needs to be on the parent element):

xml_add('inside', id_('element_parent'), '<div xmlns="http://www.w3.org/1999/xhtml"><input type="text" /><input type="button" /></div>');

Dynamic reusable code:

function id_(id) {return (document.getElementById(id)) ? document.getElementById(id) : false;}

function xml_add(pos, e, xml)
{
 e = (typeof e == 'string' && id_(e)) ? id_(e) : e;

 if (e.nodeName)
 {
  if (pos=='after') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e.nextSibling);}
  else if (pos=='before') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
  else if (pos=='inside') {e.appendChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true));}
  else if (pos=='replace') {e.parentNode.replaceChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
  //Add fragment and have it returned.
 }
}

This is what DocumentFragment was meant for.

var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
    frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);

document.createDocumentFragment, .childNodes


<div id="Result">
</div>

<script>
for(var i=0; i<=10; i++){
var data = "<b>vijay</b>";
 document.getElementById('Result').innerHTML += data;
}
</script>

assign the data for div with "+=" symbol you can append data including previous html data


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to innerhtml

React.js: Set innerHTML vs dangerouslySetInnerHTML Angular 2 - innerHTML styling How do I clear inner HTML Show/hide 'div' using JavaScript How to get the innerHTML of selectable jquery element? Cannot set property 'innerHTML' of null Add/remove HTML inside div using JavaScript Javascript - Replace html using innerHTML Add inline style using Javascript It says that TypeError: document.getElementById(...) is null