javascript - Toggle button that changes DOM -


i'm trying make button that, when clicked, can change text above it. but, want make when press again, change back. here's code i've got far, button isn't doing anything.

<!doctype.html>  <html>    <head>  </head>    <body>    <h1>javascript</h1>    <p id="display">change text!</p>    <button onclick="writeme()">click me!</button>  </body>  <script>    function writeme() {      if (document.getelementbyid("display") === "change text!") {        document.getelementbyid("display").innerhtml = "hello world!";      } else if (document.getelementbyid("display") === "hello world!") {        document.getelementbyid("display").innerhtml = "change text!";      }    }  </script>    </html>

thank you!

document.getelementbyid() returns element, it's never equal any string.

use proper event handler, , check elements textcontent property instead, , set property if want change text.
if wanted add actual html, you'd use innerhtml instead.

document.getelementbyid('mybutton').addeventlistener('click', writeme)    function writeme() {    var display = document.getelementbyid("display");      if ( display.textcontent === "change text!" ) {          display.textcontent = "hello world!";          } else if ( display.textcontent === "hello world!" ) {          display.textcontent = "change text!";          }  }
<h1>javascript</h1>  <p id="display">change text!</p>  <button id="mybutton">click me!</button>

there's dry'er way write if statements, verbose, , should easy read.


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -