user3763906
user3763906

Reputation: 13

JavaScript not working when using innerHTML

What is wrong with below code? I've added a button. And on the button's onclick event, I'm calling the script to change the value of p tag.

In the script, I'm trying to set the value od p tag using its ID attribute.

But nothing is changing if I click on the button.

Tested in different browsers, still no result.

Here is the code:

<HTML>
<BODY>
<INPUT TYPE="BUTTON" onclick="changeValue()" VALUE="Change Value" />
<P ID="demo">Initial Value</P>
<SCRIPT>
function changeValue() {
  document.getElementByID("demo").innerHTML="Value Changed"
}
</SCRIPT>
</BODY>
</HTML>

Upvotes: 1

Views: 67

Answers (3)

blizzrdof77
blizzrdof77

Reputation: 383

All of these answers give you the answer to your question - the problem with your code is the "getElementByID" function should be "getElementById", as JavaScript (like almost every programming and scripting language) is case sensitive. And technically, you should include a semicolon, but it will still work in this case without it.

Replace the element with the following (as @user3739658 provided):

 function changeValue() {
   document.getElementById("demo").innerHTML="Value Changed";
 }

Then of course you would need to call that function:

changeValue();

If you want to make it a dynamic function, pass these parameters:

 function changeValue(id, newValue) {
   document.getElementById(id).innerHTML=newValue;
 }

Then you could call it like this:

 <script>
   changeValue('element-id','This is the new value'); 
 </script>

Upvotes: 0

imbondbaby
imbondbaby

Reputation: 6411

function changeValue() {
  document.getElementById("demo").innerHTML="Value Changed";
}

You have the "d" in ID capitalized and add a ";" at the end and try it :)

Upvotes: 1

Gokul Nath KP
Gokul Nath KP

Reputation: 15574

It is getElementById with a lower case "d".

getElementById()

Note: JavaScript is case sensitive.

Upvotes: 4

Related Questions