Reputation: 185893
How to append a HTML string such as
var str = '<p>Just some <span>text</span> here</p>';
to the <div>
with the id test
?
(Btw div.innerHTML += str;
is not acceptable.)
Upvotes: 209
Views: 352972
Reputation: 1
The answer to my Question was just this; a simple Map with an empty value; and all I can get is a very heavy answer and not precise. I wonder who closed my question... didn't even bother to read
"use strict"
try {
const fruits = new Map([["Banana",""],["Apples", ""], ["Orange"," "]]);
let text = "<h1>Fruits</h1>" + "<ul>";
fruits.forEach(function(value, key){
text += "<li>" + key + value + "<br>" + "</li>"
});
text +="</li> ";
document.getElementById('demo').innerHTML = text;
} catch(err){
document.getElementById('theError').innerHTML = err;
}
Upvotes: -1
Reputation: 55382
Use insertAdjacentHTML
which is supported in all current browsers:
div.insertAdjacentHTML( 'beforeend', str );
The position parameter beforeend
will add inside the element, after its last child.
Live demo: http://jsfiddle.net/euQ5n/
Upvotes: 408
Reputation: 92367
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.
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)
You can replay test in your machine here
function A() {
container.innerHTML += '<p>A: Just some <span>text</span> here</p>';
}
function B() {
container.innerHTML = '<p>B: Just some <span>text</span> here</p>';
}
function C() {
$('#container').append('<p>C: Just some <span>text</span> here</p>');
}
function D() {
var p = document.createElement("p");
p.innerHTML = 'D: Just some <span>text</span> here';
container.appendChild(p);
}
function E() {
var p = document.createElement("p");
var s = document.createElement("span");
s.appendChild( document.createTextNode("text ") );
p.appendChild( document.createTextNode("E: Just some ") );
p.appendChild( s );
p.appendChild( document.createTextNode(" here") );
container.appendChild(p);
}
function F() {
container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');
}
A();
B();
C();
D();
E();
F();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This snippet only for show code used in test (in jsperf.com) - it not perform test itself.
<div id="container"></div>
Upvotes: 50
Reputation: 92367
Shortest - 18 chars (not confuse +=
(mention by OP) with =
more details here)
test.innerHTML=str
var str = '<p>Just some <span>text</span> here</p>';
test.innerHTML=str
<div id="test"></div>
Upvotes: -1
Reputation: 3885
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:
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.
Upvotes: 2
Reputation: 31
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
function append(element, str)
{
var child = document.createElement('someshittyuniquetag');
child.innerHTML = str;
element.appendChild(child);
child.outerHTML = child.outerHTML.replace(/<\/?someshittyuniquetag>/, '');
// or Even child.outerHTML = child.innerHTML
}
<div id="testit">
This text is inside the div
<button onclick="append(document.getElementById('testit'), '<button>dadasasdas</button>')">To div</button>
<button onclick="append(this, 'some text')">to this</button>
</div>
Upvotes: 1
Reputation: 69
This can solve
document.getElementById("list-input-email").insertAdjacentHTML('beforeend', '<div class=""><input type="text" name="" value="" class="" /></div>');
Upvotes: 1
Reputation: 7828
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.
Upvotes: 12
Reputation: 490163
Is this acceptable?
var child = document.createElement('div');
child.innerHTML = str;
child = child.firstChild;
document.getElementById('test').appendChild(child);
But, Neil's answer is a better solution.
Upvotes: 35
Reputation: 8026
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.)
Upvotes: 4
Reputation: 10047
Why is that not acceptable?
document.getElementById('test').innerHTML += str
would be the textbook way of doing it.
Upvotes: 0