skip to Main Content

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


  1. Chosen as BEST ANSWER

    I had accidentally called the wrong ID, The code works fine now.


  2. You’re trying to change src from a object called img, but what you have is image

    Just change

    document.getElementById("img").src="image.png";
    

    to

    document.getElementById("image").src="image.png";
    
    Login or Signup to reply.
  3. this line is wrong

    document.getElementById("img").src="image.png";

    it should be:

    document.getElementById("image").src="image.png";

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search