[javascript] Appending HTML string to the DOM

How to append this HTML string

var str = '<p>Just some <span>text</span> here</p>';

to the DIV with the ID 'test' which is in the DOM?

(Btw div.innerHTML += str; is not acceptable.)

This question is related to javascript html dom browser

The answer is


The right way is using insertAdjacentHTML. In Firefox earlier than 8, you can fall back to using Range.createContextualFragment if your str contains no script tags.

If your str contains script tags, you need to remove script elements from the fragment returned by createContextualFragment before inserting the fragment. Otherwise, the scripts will run. (insertAdjacentHTML marks scripts unexecutable.)


Quick Hack:


<script>
document.children[0].innerHTML="<h1>QUICK_HACK</h1>";
</script>

Use Cases:

1: Save as .html file and run in chrome or firefox or edge. (IE wont work)

2: Use in http://js.do

In Action: http://js.do/HeavyMetalCookies/quick_hack

Broken down with comments:

<script>

//: The message "QUICK_HACK" 
//: wrapped in a header #1 tag.
var text = "<h1>QUICK_HACK</h1>";

//: It's a quick hack, so I don't
//: care where it goes on the document,
//: just as long as I can see it.
//: Since I am doing this quick hack in
//: an empty file or scratchpad, 
//: it should be visible.
var child = document.children[0];

//: Set the html content of your child
//: to the message you want to see on screen.
child.innerHTML = text;

</script>

Reason Why I posted:

JS.do has two must haves:

  1. No autocomplete
  2. Vertical monitor friendly

But doesn't show console.log messages. Came here looking for a quick solution. I just want to see the results of a few lines of scratchpad code, the other solutions are too much work.


Shortest - 18 chars (not confuse += (mention by OP) with = more details here)

test.innerHTML=str

_x000D_
_x000D_
var str = '<p>Just some <span>text</span> here</p>';_x000D_
_x000D_
test.innerHTML=str
_x000D_
<div id="test"></div>
_x000D_
_x000D_
_x000D_


InnerHTML clear all data like event for existing nodes

append child with firstChild adds only first child to innerHTML. For example if we have to append:

 <p>text1</p><p>text2</p>

only text1 will show up

What about this:

adds special tag to innerHTML by append child and then edit outerHTML by deleting tag we've created. Don't know how smart it is but it works for me or you might change outerHTML to innerHTML so it doesn't have to use function replace

_x000D_
_x000D_
function append(element, str)_x000D_
{_x000D_
_x000D_
  var child = document.createElement('someshittyuniquetag');_x000D_
  _x000D_
  child.innerHTML = str;_x000D_
_x000D_
  element.appendChild(child);_x000D_
_x000D_
  child.outerHTML = child.outerHTML.replace(/<\/?someshittyuniquetag>/, '');_x000D_
_x000D_
// or Even child.outerHTML = child.innerHTML_x000D_
_x000D_
_x000D_
  _x000D_
}
_x000D_
<div id="testit">_x000D_
This text is inside the div_x000D_
<button onclick="append(document.getElementById('testit'), '<button>dadasasdas</button>')">To div</button>_x000D_
<button onclick="append(this, 'some text')">to this</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


This can solve

 document.getElementById("list-input-email").insertAdjacentHTML('beforeend', '<div class=""><input type="text" name="" value="" class="" /></div>');

Is this acceptable?

var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);

jsFiddle.

But, Neil's answer is a better solution.


The idea is to use innerHTML on an intermediary element and then move all of its child nodes to where you really want them via appendChild.

var target = document.getElementById('test');
var str = '<p>Just some <span>text</span> here</p>';

var temp = document.createElement('div');
temp.innerHTML = str;
while (temp.firstChild) {
  target.appendChild(temp.firstChild);
}

This avoids wiping out any event handlers on div#test but still allows you to append a string of HTML.


Why is that not acceptable?

document.getElementById('test').innerHTML += str

would be the textbook way of doing it.


Performance

AppendChild (E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML(F) is fastest on firefox. The innerHTML= (B) (do not confuse with += (A)) is second fast solution on all browsers and it is much more handy than E and F.

Details

Set up environment (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)

enter image description here

  • on Chrome E (140k operations per second) is fastest, B (47k) and F (46k) are second, A (332) is slowest
  • on firefox F (94k) is fastest, then B(80k), D (73k), E(64k), C (21k) slowest is A(466)
  • on Safari E(207k) is fastest, then B(89k), F(88k), D(83k), C (25k), slowest is A(509)

You can replay test in your machine here

_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML += '<p>A: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML = '<p>B: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  $('#container').append('<p>C: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
function D() {_x000D_
  var p = document.createElement("p");_x000D_
  p.innerHTML = 'D: Just some <span>text</span> here';_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function E() {    _x000D_
  var p = document.createElement("p");_x000D_
  var s = document.createElement("span"); _x000D_
  s.appendChild( document.createTextNode("text ") );_x000D_
  p.appendChild( document.createTextNode("E: Just some ") );_x000D_
  p.appendChild( s );_x000D_
  p.appendChild( document.createTextNode(" here") );_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
This snippet only for show code used in test (in jsperf.com) - it not perform test itself. _x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_


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 dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to browser

How to force reloading a page when using browser back button? How do we download a blob url video How to prevent a browser from storing passwords How to Identify Microsoft Edge browser via CSS? Edit and replay XHR chrome/firefox etc? Communication between tabs or windows How do I render a Word document (.doc, .docx) in the browser using JavaScript? "Proxy server connection failed" in google chrome Chrome - ERR_CACHE_MISS How to check View Source in Mobile Browsers (Both Android && Feature Phone)