PDA

View Full Version : Very simple JS function problem



tk403
11-06-2008, 02:22 AM
I have a very simple function which I cannot figure out.

Here's the JS
----
function replaceHeading() {
var heading = document.getElementById("initial_heading");
alert(heading.nodeName);
}
----
and here's the relevant HTML
----
<div id="content">
<h1 id="initial_heading" class="specialh1">[xyz page]</h1>
<p><img id="temp" src="images/zone.jpg" alt="Zone sign" width="400" height="267" /></p>
<h1 class="specialh1"><a href="index.html">[.com]</a></h1>
</div>
----
shouldn't alert(heading.nodeName) return h1? I get no JS message at all when I load the page.

clueful
11-06-2008, 03:02 AM
I
shouldn't alert(heading.nodeName) return h1? I get no JS message at all when I load the page.Are you actually calling your function anywhere?
It has to be called after the relevant element has rendered.

magicyte
11-06-2008, 11:56 PM
This function you provided should work. Here is some code I created for you to replace it:


<!-- your doctype up here -->
<html>
<head>
<title></title>
<script type="text/javascript">
function replaceHeading() {
window.alert(document.getElementById("initial_heading").nodeName);
}
</script>
<style type="text/css">
</style>
</head>
<body onload="replaceHeading()">
<div id="content">
<h1 id="initial_heading" class="specialh1">[xyz page]</h1>
<p><img id="temp" src="images/zone.jpg" alt="Zone sign" width="400" height="267" /></p>
<h1 class="specialh1"><a href="index.html">[.com]</a></h1>
</div>
</body>
</html>

This, in my browser (IE8 Beta), works and alerts "H1". You probably didn't inlude onload="replaceHeading()" in the body tag.

-magicyte

tk403
11-07-2008, 02:25 AM
Thanks!!

I did call the function initially, but after the close of the function. I had:

window.onload = replaceHeading();

after I closed out the function. I also have to call the function from the <body> tag?

magicyte
11-07-2008, 02:33 AM
after I closed out the function. I also have to call the function from the <body> tag?

No. You can do it either way. onload in the body tag is just for HTML. You can do it in JavaScript too, but don't do it at the same time.

You are welcome.

Made a clumsy error.
-magicyte

rangana
11-07-2008, 02:57 AM
window.onload = replaceHeading(); best be document.onload = replaceHeading;

-magicyte

Mind explaining why?

I don't think document.onload will work:


document.onload=test;
function test()
{
alert('Hello World');
}

magicyte
11-07-2008, 11:23 PM
Mind explaining why?

My mistake. It IS window.onload.

-magicyte