0

Replacing child multiple times problems..

Can't seem to click on my button functions to change my text more than one time total. Here is my HTML code, followed by my JavaScript. Perhaps I need an Event handler? HTML <body> <button><div id="demo"> <p id="p1">You are at Home.</p> </button> </div> <div> <button onclick="gotown()">GO TO TOWN</button> <button onclick="gohome()">GO HOME</button> </div> </body> JAVASCRIPT function gotown() { var p = document.createElement("p"); var node = document.createTextNode("You are at Town"); p.appendChild(node); var parent = document.getElementById("demo"); var child = document.getElementById("p1"); parent.replaceChild(p, child); }; function gohome() { var p = document.createElement("p"); var node = document.createTextNode("You are Home"); p.appendChild(node); var parent = document.getElementById("demo"); var child = document.getElementById("p1"); parent.replaceChild(p, child); };

7th Feb 2017, 1:19 AM
Aubrey Shannon
Aubrey Shannon - avatar
1 Odpowiedź
+ 1
Your HTML tags are overlapped. It looks like you have an unnecessary button tag mixed in with your demo div. In your functions you are creating a new p tag element and then adding a text node as a child to it. Then you're getting the overlapped demo div and replacing its child p tag with the id of p1 with the newly created p tag and its text node. Notice that the new p tag is never given the id that you use in your functions. For what you're doing here you could simplify it by using 1 button that changes the .innerHtml of the p tag with the id of p1, cutting down both your html and your Javascript code. You could also change the text of the button within its onclick function. No additional event handlers should be needed.
7th Feb 2017, 3:07 AM
ChaoticDawg
ChaoticDawg - avatar