magna_nz
magna_nz

Reputation: 1273

Getting text to change

Very new to Javascript.

Trying to get the text "Paragraph changed" to change to "New" when button is clicked. Not too sure why this is happening.

Thanks

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>
<p id="demo">My first paragraph.</p>

<script>
function firstFunction(){
    document.getElementByID("demo").innerHTML="New";
</script>

<button type="button" onclick="firstFunction()">Try it</button>

</body>
</html> 

Upvotes: 1

Views: 49

Answers (2)

David Mann
David Mann

Reputation: 2270

Your script position doesn't matter, though it is best to place it just before you close the body tag for loading issues.

Your issue is two fold. First make sure that when declaring a function you close your curly braces. Second the function name is getElementById not getElementByID JavaScript is case sensitive.

<!DOCTYPE html>
<html>

<body>

  <h1>My First Web Page</h1>
  <p id="demo">My first paragraph.</p>

  <script>
    function firstFunction() {
      <!-- Id is not capitalized -->
      document.getElementById("demo").innerHTML = "New";
    } <!-- important curly brace -->
  </script>

  <button type="button" onclick="firstFunction()">Try it</button>

</body>

</html>

Upvotes: 0

Ishamael
Ishamael

Reputation: 12795

There are two issues I can spot immediately:

  1. You do not have a closing curly brace in your function

  2. The getElementById function is misspelled, the last letter should not be capitalized.

You would see both issues in the browser console as you load the page. It is often displayed if you press ctrl+shift+I, Ctrl+shift+J or F12, or search for it in the tools menu. When you open it, go to console tab and you will see the errors that occur.

Here's more details on how to open the console:

https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers

Upvotes: 3

Related Questions