So I have this string:
var textToBeRendered='<h1>I am a string of text</h1>';
If I have a div on the DOM, how would I be able to render the string to the div element as an actual header?
So the DOM would contain:
<div>
<h1>I am a string of text</h1>
</div>
-
Possible duplicate of Add/remove HTML inside div using JavaScriptDr. Stitch– Dr. Stitch2016年02月11日 05:48:12 +00:00Commented Feb 11, 2016 at 5:48
6 Answers 6
Try This ^_^ :
var textToBeRendered='<h1>I am a string of text</h1>';
document.getElementById("demo").innerHTML = textToBeRendered
<div id="demo">
<h1>I am a string of text</h1>
</div>
1 Comment
Use document.createElement to create childNode. textContent to put a text inside the newly created element. Then use appendChild to append with the parent
HTML
<div id="somId">
</div>
JS
var textToBeRendered= document.createElement('h1');
textToBeRendered.textContent = "I am a string of text";
document.getElementById('somId').appendChild(textToBeRendered);
Comments
If you consider using jQuery, you could use jQuery.parseHTML()
Comments
var textToBeRendered='<h1>I am a string of text</h1>';
var div = document.createElement("div");
div.innerHTML = textToBeRendered;
document.body.appendChild(div);
Comments
you can use JQUERY to do that, the following code will help you
<div id="myHeader">
</div>
<script>
$("myHeader").html("<h1>I am a string of text</h1>")
</script>
Comments
I find insertAdjacentHTML to be the most flexible. The first param is where it should be inserted in relation to the element it's called on. The second param is the string. you could even use it like this. div.insertAdjacentHTML('afterbegin', '<h1>I am a string of text</h1>');
(function(div) {
var textToBeRendered = '<h1>I am a string of text</h1>';
div.insertAdjacentHTML('afterbegin', textToBeRendered);
}(document.querySelector('div')));
<div>
</div>