I have a website with a series of buttons, when these buttons are clicked, I want it to change the innerHTML of multiple elements, however, when the buttons are clicked, nothing happens.
function changeName() {
document.getElementById("img").src="image.png";
document.getElementById("name").innerHTML = "name";
document.getElementById("date").innerHTML = "date";
document.getElementById("hook").innerHTML = "hook";
document.getElementById("text").innerHTML = "“text";
}
<button class="button" onclick="changeName()">Name</button>
<img src="image2.png" id="image" alt="Portrait">
<h1 id="name">test</h1>
<p id="date">test</p>
<h1 id="hook">test</h1>
<p id="text">test</p>
And I am just wondering what I could be doing wrong, I am semi-new to JavaScript and I expected problems to arise, however, it seems to me that my code should work. (In theory) I have tried changing the names of the elements and the name of the function to try and see if it would work however nothing I seem to do will change the innerHTML. I have also run my JavaScript code through JSHint only to find no issues except an unused variable.
3
Answers
I had accidentally called the wrong ID, The code works fine now.
You’re trying to change
src
from a object calledimg
, but what you have isimage
Just change
to
this line is wrong
document.getElementById("img").src="image.png";
it should be:
document.getElementById("image").src="image.png";