Cycle through all DIVs, please help

M

Marc

Hi to all,

I have several DIVs in a page, each has a unique name. I'd need a method to
cycle through all DIVs so that I can change their style. For example, let's
say I need to set a red background to DIVs whose name begins with "a". This
is the pseudo code:

For Each Div in The Page
If Div's name starts with 'a' then set Div's background to Red
Next

How can I translate this 'pseudocode' into real javascript code?
Thank you!

Marc
 
M

Martin Honnen

Marc said:
I have several DIVs in a page, each has a unique name. I'd need a method to
cycle through all DIVs so that I can change their style. For example, let's
say I need to set a red background to DIVs whose name begins with "a". This
is the pseudo code:

For Each Div in The Page
If Div's name starts with 'a' then set Div's background to Red
Next

How can I translate this 'pseudocode' into real javascript code?

<div> elements in HTML don't have a name attribute so you should use the
id attribute e.g.
<div id="a1">...</div>
You can find out all the <div> elements in the document with
var divs = document.getElementsByTagName('div');
then loop
for (var i = 0; i < divs.length; i++) {
var div = divs;
if (div.id.indexOf('a') == 0 && div.style) {
div.style.backgroundColor = 'red';
}
}
 
I

Ivo

I have several DIVs in a page, each has a unique name. I'd need a method to
cycle through all DIVs so that I can change their style. For example, let's
say I need to set a red background to DIVs whose name begins with "a". This
is the pseudo code:

For Each Div in The Page
If Div's name starts with 'a' then set Div's background to Red
Next

How can I translate this 'pseudocode' into real javascript code?
Thank you!

Marc

var els = document.getElementsByTagName('div');
var i = els.length; while( i-- ) {
if( els.indexOf('a') === 0 ) {
els.style.background = 'red';
}
}

You could use an incrementing "for" loop, but a decrementing "while" is
faster.
HTH
Ivo
 
I

Ivo

"Ivo"wrote
if( els.indexOf('a') === 0 ) {


Too fast! That should of course have been:
if( els.name.indexOf('a') === 0 ) {
if you are happy with named div's. I 'd use id's.
Ivo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top