View Full Version : dynamic name

07-07-2006, 11:18 PM
Hi there,

I have few divs on my site, each on is called 'Description' and has a number attached to it (Description1, Description2, Description3 and so on).

On onclick event, I want to change the style of all of those divs. I have this little piece of coding:

function hideDesc()
for(i = 1; i < 20; i++){
document.getElementById('Description'+i).className = 'hidden';
and it does not work, of course.

Can anyone help me out here?
Also, the number of divs varies, is there a way to count them all instead of using 'hard' number?

Thank you in advance!

07-08-2006, 03:03 AM
You can count the number of divs using document.getElementsByTagName("DIV") This will store all the divs on the page in an array.

You can then loop through that array to find the divs who's ids match "Description" followed by a number. (...match(/^Description\d/))

All the divs who's ids match will then be hidden.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">

<script type="text/javascript">
// <![CDATA[ //
function hideDesc(){
var divs = document.getElementsByTagName("DIV");
for(var i = 0; i < divs.length; i++){
divs[i].className = 'hidden';
// ]]> //

<div id="Description1" class="shown">Description1</div>
<div id="Description2" class="shown">Description2</div>
<div id="Description3" class="shown">Description3</div>
<div id="Description4" class="shown">Description4</div>
<div id="Different" class="shown">This is not a description div.</div>
<button onclick="hideDesc()">Hide Divs</button>

07-08-2006, 03:18 AM
Hey Jud,

thank you very much for your reply. I have solved my problem using ol' good (and my beloved :) ) PHP.

I just run the loop in PHP and echoed out the whole javascript function to hide all opened divs inside that loop.

Works like a charm :thumbsup:

Thanks for your time!

originally I forgot to mention that each and every div's name is created dynamically (I mean the number of it), so I don't really think that javascript alone could manage it. But again: when driven by PHP - all stuff is just groo-hoo-vee-hee :)