javascript - Why is document.getElementById() returning a null value when I know the ID exists? -



javascript - Why is document.getElementById() returning a null value when I know the ID exists? -

i'm working on custom javascript cms template @ work. want able create <li> element on page receive class of "current" page only. in global page head have this:

<script type="text/javascript"> function makecurrent(id) { var current = document.getelementbyid(id); current.setattribute("class", "current"); // browsers current.setattribute("classname", "current"); // ie } </script>

then in each individual page <head>, have this:

<script type="text/javascript">makecurrent("undergraduate")</script>

on page have nav <ul>, like:

<li id="undergraduate"><a href="...">undergraduate program</a></li> <li id="graduate"><a href="...">graduate program</a></li> etc.

when load page, class not applied. when in firebug console, gives error message:

current null (x) current.setattribute("class", "current");

i'm still getting hang of writing solid, raw javascript (learning backwards after jquery, know how goes), want write in js. idiotic newbie error making?

thanks everyone!

the element does not exist yet when script beingness evaluated. set in body's onload handler or instead, executes 1 time dom in place.

an illustration of how without touching markup:

function callwhenloaded(func) { if (window.addeventlistener) { window.addeventlistener("load", func, false); } else if (window.attachevent) { window.attachevent("onload", func); } } callwhenloaded(function() { makecurrent("undergraduate"); });

javascript getelementbyid

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -