...

View Full Version : get multiple elements by class



Greg-J
04-24-2006, 09:42 PM
The short of it is that I am trying to change the background color of all elements with a particular class name. I know there is no getElementsByClassName (wouldn't it be nice if there were?), but is there a simple way to do it?

Alternatively, is there a way to apply changes to multiple id's?
Edit/Delete Message

Beagle
04-24-2006, 10:05 PM
Well:

1) If you're trying to change the background color of all elements with a specific class, you can use JavaScript to modify the class itself: http://www.javascriptkit.com/domref/stylesheet.shtml

2) Check out attribute crawler: http://neo.dzygn.com/demos/attributecrawler.php

Greg-J
04-24-2006, 10:10 PM
1. I am using a color picker to change the background color - so I don't think changing the style is a very viable option.

2. I'm new to .js, so that attribute crawler is way over my head.


But thank you for your time.

Beagle
04-24-2006, 10:27 PM
if you're using a color picker, what you do is use javascript to modify the rule for the class that defines the background color. I don't see any problems there.

The attribute crawler is a script you put on your page that gives you the ability to call special functions like getElementsByClassName("class") it just does it in a round-about way so as to not suffer terrible speed problems, which you will run into inevitably. Go with option 1.

Greg-J
04-25-2006, 02:06 AM
Thank you for explaining all this to me.

I think I am going to with changing the stylesheet rules. I'm still very fuzzy on how to this, but I'm trying to make sense of it.

Kor
04-25-2006, 10:49 AM
The short of it is that I am trying to change the background color of all elements with a particular class name. I know there is no getElementsByClassName (wouldn't it be nice if there were?), but is there a simple way to do it?

Alternatively, is there a way to apply changes to multiple id's?
Edit/Delete Message


...
var el = document.getElementsByTagName('*');
for(var i=0;i<el.length;i++){
el[i].className=='myClass'?el[i].style.backgroundColor='#ff0000':null;
}
...


Second problem? Well, id may not be multiple. id must be unique on the same page/session.

DHTML Kitchen
05-01-2006, 08:01 PM
Hey,

We discussed this to death on dhtmlcentral a few years back. I believe we decided that using == was bad because it doesn't work well with multiple classes.

indexOf will not work with consistant reliability, either.

There's two approaches that will work:
1) split the className estring and loop through the array
2) use regex.test(className);

I just figured out a way to do it using Array.filter. If you're supporting IE, you'll have to add Array.filter. There's an example posted on my site.

Garrett



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum