48

I'm trying to do this with pure javascript, not with jquery. I have a div that has an id test and contains other divs inside it. How do I empty the content of this div and replace it with other html?

<div id="test">
   <div>...</div>
   <div>...</div>
   <div>...</div>
</div>

7 Answers 7

75
document.getElementById("test").innerHTML = "new content"
Sign up to request clarification or add additional context in comments.

Comments

26

clear the div:

document.getElementById('test').innerHTML = '';

replace it :

var h1 = document.createElement('h1');
h1.innerHTML = "hello world!";
document.getElementById('test').appendChild(h1);

Comments

5

Use document.getElementById('test').innerHTML = ''.

Comments

5

Off the top of my head, I think this should work....

document.getElementById("test").innerHTML = "";

1 Comment

I didn't downvote, but I think the -1 comes from innerHtml not being innerHTML. I'll upvote to counter; that's mean.
4
document.getElementById("test").innerHTML = "Some other Content";

Comments

4
var testDiv = document.getElementById("test");
testDiv.innerHTML = "<h5>It works!</h5>";

Comments

2

There's also an

Element.replaceWith()

https://developer.mozilla.org/en-US/docs/Web/API/Element/replaceWith

Comments

Your Answer

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.