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>
asked Feb 11, 2016 at 5:45
1

6 Answers 6

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>

answered Feb 11, 2016 at 5:49
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I wanted. I just had a really bad brain fart; I should've thought of this. I appreciate your help!
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

answered Feb 11, 2016 at 5:52

Comments

0

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

answered Feb 11, 2016 at 5:48

Comments

0
var textToBeRendered='<h1>I am a string of text</h1>';
var div = document.createElement("div");
div.innerHTML = textToBeRendered;
document.body.appendChild(div);
answered Feb 11, 2016 at 5:48

Comments

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>
answered Feb 11, 2016 at 5:51

Comments

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>

answered Feb 11, 2016 at 5:49

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.