Using Javascript with CSS and DOM

Hello everyone,

This is a practice script and is not meant for real world use.

I can’t get this to work. The code is suppose to change the background color of the div tag.

Any ideas?


<script type="text/javascript">
<!--
function changeColor(){
	var divTag = document.getElementsById("div");
	for (var counter = 0; counter < divTag.lenght; counter++){
		divTag[counter].style.background = "#FF0000";
	}
}
//-->
</script>
</head>

<body>
<div style="width: 200px; height: 200px;">I love soupterines</div>
<input type="button" value="Change Color" onclick="changeColor()" />
</body>

Thanks!!

Novice2010

Thanks for the contribution!!

I’ll mess around with it.

Nov

Thanks for pointing that out and sorry for the confusion, I originally had document.getElementsByTagName. But change it to ID when that wasn’t working before posting the script.

Thanks again.

Novice

This one might help you with other possibilities. It toggles the colour as you click on the button.

<html>

<head>

<script type=“text/javascript”>
<!–
// flag to keep track of colour setting
var bgColorSet=false; // global
//
function changeColor()
{ var divTag=document.getElementById(“div1”);
// check and set color if white make it red, if red make it white
var bg=(bgColorSet==false)?“F00” : “FFF”;
divTag.style.backgroundColor=bg;
// reset flag
bgColorSet=(bgColorSet)?false : true;
}
//–>
</script>
<style type=“text/css”>
<!–
#div1 {position:relative; top:2px; left:5px; width:200px; height:200px; border:1px solid #000; }
.a18B { font-size:18px; font-weight:bold; color:#000; text-indent:10px; }
–>
</style>
</head>

<body>

<div id=“div1”>
<p class=“a18B”>I love soupterines
</div>
<!-- end div1 –>
<p><input type=“button” value=“Change Color” onclick=“changeColor()”></p>

</body>

</html>

It doesn’t work because you haven’t given the DIV an id. Also, it’s [document.getElementById](http://www.tizag.com/javascriptT/javascript-getelementbyid.php) - note the spelling.

You have a spelling mistake in the for loop - look at your spelling of length. But that is not relevant, because you don’t need a for loop at all. getElementById will only return one tag. This is because the id is supposed to be unique - only one element can have a single id.