Question

EDIT: Here's the link to the JSFiddle: http://jsfiddle.net/retserrof84/aLPPv/3/

So this is definitely a stupid question, but I've been banging my head on my keyboard for a few hours now. I'm trying to use innerHTML to change the content of a div, and it's not doing anything. Here's the test HTML:

<body>
  <div id="hola">
    Hola.
  </div>
  <div>
    <a onclick="changeMe()">Click here.</a>
  </div>
</body>

Ok, and here's the JavaScript:

function changeMe() {
  document.getElementById("hola").innerHTML="Hello!";
}

And that's it. Could someone please help me see what I'm doing wrong? What's weird is I've used innerHTML and onclick in a more complicated project and it worked fine, so I know I must be making some stupid mistake.

I've searched through other answers, and the only thing I can find in those is that the function might somehow be getting called before the ID exists, but I've separated the function call and the affected element, and put the function call later, so I don't know why that would still be an issue. Any help would be appreciated.

Was it helpful?

Solution

You need to take care about left toolbox option, where you want your script (in head/ domready etc).

This is working :

<body>
  <div id="hola">
    Hola.
  </div>
  <div>
    <a onclick="changeMe()">Click here.</a>
  </div>
</body>

function changeMe() {
  document.getElementById("hola").innerHTML="Hello!";
}

http://jsfiddle.net/59DFY/

OTHER TIPS

You're most likely not adding that JS file in your head (or body) which is why it's saying your function is not defined in the Fiddle. Be sure to link to it.

<head>
  <script src="link-to-file"></script>
</head>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top