2

I have a quick question. I'm not sure exactly what this is called, but how do you write a div into a div? Example, I want to create a simple game that stays on the same page. When a button is clicked to move on to the next part of the game, the original div will be erased and a new one put on top of that.

So, lets say I have a div called "start" and another called "option 1". Option 1 would be hidden, while start is displayed as the home page. When you click a button on the "start" div, it writes the "option 1" div over that, erasing the first div.

My HTML code:

<div id="start">
<button class="button" onclick="swordsman()">Choose Swordsman</button>
</div>

My JS:

function swordsman()
{
document.getElementById("start")writeDiv.id="option 1"
}

And that is where I am stuck, I don't know the code to replace a div with another div. It's purely a guess.

I am new to JavaScript, so excuse my stupidity.

3
  • 3
    You can replace the contents using innerHTML - developer.mozilla.org/en-US/docs/Web/API/Element.innerHTML Commented Mar 4, 2014 at 12:29
  • Nick, thanks, although I didn't know how to write the div into the html with that. I didn't know the exact way to code it. Commented Mar 4, 2014 at 12:33
  • 1
    @Timby Look at BenjaminRH's answer..... Commented Mar 4, 2014 at 12:34

2 Answers 2

4

You can use innerHTML like so:

function swordsman() {
    var otherDiv = document.getElementById("option-1").outerHTML; // Get the option 1 div
    document.getElementById("start").innerHTML = otherDiv; // Replace the contents of the start div with the option 1 div
}
Sign up to request clarification or add additional context in comments.

Comments

-1

You have an syntaxerror

  document.getElementById("start")writeDiv.id="option 1"

should be document.getElementById("start").writeDiv.id="option 1"

but i think there is no function "writeDiv", but you can use the innerHTML atribute:

  document.getElementById("start").innerHTML ='<div id = "option 1"></div>';

look also for jQuery, DOM handling will be much easier ;)

you can check your code for syntaxerros by using browsers javascroipt console

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.