Ad

GetElementById/InnerHTML Function Not Working

- 1 answer

I'm playing around with Javascript to get back in the swing of things for my second semester web class that recently started, and I've run into an issue getting getElementById and innerHTML to work.

Basically, I want to populate an empty h1 with an Animal name

function favAnimal()
      {
         document.getElementById("animal").innerHTML="cat"
      }
<h1 id="animal" onload="favAnimal()">Favourite Animal Placeholder</h1>

The above does not change anything. If the h1 is empty the result is the same. I've also tried with a <div> to rule out an issue using specific elements.

All help is appreciated and thanks in advance!

Ad

Answer

An <h1> tag does not have an onload event handler so your function is never being called.

You can use the onload handler for the <body> tag or set up some other event handler to assign your function to.

If you want your code to be triggered when the document is loaded, you can use one of these:

window.addEventListener("load", favAnimal);       // all page resources loaded
document.addEventListener("DOMContentLoaded", favAnimal);   // HTML done parsing

If you just want your script to be executed right after your <h1> tag has been loaded, you can just place a call to the script right after the tag. The page is parsed/executed in order so that any script will always be able to reference HTML elements that come before it in the document:

<h1 id="animal">Favourite Animal Placeholder</h1>
<script>favAnimal()</script>

Here are some of the things I'm aware of that have a load event:

window
<img>
<body>
<iframe>
<link>
<script>
<embed>
<object>
<video>
<audio>
XMLHttpRequest

And, pretty much any other HTML tag that has a src or href attribute except <a>. The idea is that if the tag is loading some external resource, then there is a load event to know when it is done loading that external resource. If the tag is not loading an external resource, there is probably not a load event for it.

Ad
source: stackoverflow.com
Ad