PDA

View Full Version : Simple code that doesnt work. Please help...



acroporas
Jun 21st, 2007, 03:46 AM
Sorry for the non-descriptive title, but I'm very new to javascript and I have no idea where the problem(s) are to ask a more descriptive question.

Can someone tell me what I am doing wrong.

html page includes the following:


<div class="test">testing 1</div>
<div class="test">testing 2</div>
<div class="test">testing 3</div>
<div class="test">testing 4</div>
<div class="test">testing 5</div>

here is a script that does not work as I expect it to.


all_divs = document.getElementsByTagName("div");

for ( i=0; i <= all_divs.length; i++) {
window.alert ( all_divs[i].className );

if ( all_divs[i].className == "test" ) {
window.alert( "There was a div named test on the page" );
}
}


The first alert is triggered 5 times saying test.
The second alert is never triggered.

_Aerospace_Eng_
Jun 21st, 2007, 04:08 AM
The only issue I see is that you are using i <= all_divs.length; You want < not <=. <= will throw an error because there are only 5 divs not 6 so all_divs[5].className will give you something like null or undefined.
Also you have to call the script onload. You can't call it while the document is loaded because of the div may not be part of the DOM yet. Try this

<script type="text/javascript">
window.onload = function()
{
all_divs = document.getElementsByTagName("div");

for (i = 0; i < all_divs.length; i++)
{
window.alert (all_divs[i].className);
if (all_divs[i].className == "test")
{
window.alert("There was a div named class on the page");
}
}
}
</script>

acroporas
Jun 21st, 2007, 04:59 AM
Thanks for looking at it.

I changed the <= to < and had it run on load, but it still does not make it to the inner alert.

_Aerospace_Eng_
Jun 21st, 2007, 05:02 AM
It does when I tested it so you are likely doing something incorrectly.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
window.onload = function()
{
all_divs = document.getElementsByTagName("div");

for (i = 0; i < all_divs.length; i++)
{
window.alert (all_divs[i].className);
if (all_divs[i].className == "test")
{
window.alert("There was a div named class on the page");
}
}
}
</script>
</head>

<body>
<div class="test">testing 1</div>
<div class="test">testing 2</div>
<div class="test">testing 3</div>
<div class="test">testing 4</div>
<div class="test">testing 5</div>
</body>
</html>

acroporas
Jun 21st, 2007, 05:11 AM
Yes, when I past that in it worked.

Thanks.