1

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>
elloM8
  • 164
  • 1
  • 7
  • Possible duplicate of [Add/remove HTML inside div using JavaScript](http://stackoverflow.com/questions/17650776/add-remove-html-inside-div-using-javascript) – Dr. Stitch Feb 11 '16 at 05:48

6 Answers6

4

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>
solimanware
  • 2,952
  • 4
  • 20
  • 40
  • This is what I wanted. I just had a really bad brain fart; I should've thought of this. I appreciate your help! – elloM8 Feb 11 '16 at 05:53
2

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);

EXAMPLE

brk
  • 48,835
  • 10
  • 56
  • 78
0

If you consider using jQuery, you could use jQuery.parseHTML()

0
var textToBeRendered='<h1>I am a string of text</h1>';
var div = document.createElement("div");
div.innerHTML = textToBeRendered;
document.body.appendChild(div);
Sagi
  • 8,972
  • 3
  • 33
  • 41
0

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>
colecmc
  • 3,133
  • 2
  • 20
  • 33
0

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>
Alaa Abuzaghleh
  • 1,023
  • 6
  • 11