Dynamo

David Ledger

18 Feb 2010, 7:35 pm

Change visibility by class

Is there a JavaScript method similar to getElementById(“id”) that returns an array of elememts in a CSS class?

Or better still, an onClick way of dynamically changing a style property of all elements with a CSS class?

David

David Ledger - Freelance Unix Sysadmin in the UK. HP-UX specialist of hpUG technical user group (www.hpug.org.uk) email@hidden www.ivdcs.co.uk

quote

waltd

18 Feb 2010, 8:48 pm

In Prototype, there is the double-dollar function, which will return an array (always an array) of elements that match whatever CSS3 selector you can cook up.

$$('div.foo') //--> returns an array of divs with the classname 'foo'
$$('input[type="checkbox"][checked="checked"]') //-->returns an array
of checked checkboxes
$$('p:first-child') //--> returns an array of paragraphs that are the
first child of their nearest parent

Since these elements have been “extended” by Prototype, you have access to the rich library of iterators and “finders” that allow you to further tweak your results, or you can apply the same method to all of them at once using invoke() as in:

$$('p.hideMe').invoke('hide');

If you’re not using Prototype, then there is the standard getElementsBySelector(), but you may have to do some serious testing to make sure that IE understands what you mean. The good folks at Prototype have already done that work for you and bottled it up so it’s more accessible and you don’t have to repeat yourself.

Walter

On Feb 18, 2010, at 3:35 PM, David Ledger wrote:

Is there a JavaScript method similar to getElementById(“id”) that returns an array of elememts in a CSS class?

Or better still, an onClick way of dynamically changing a style property of all elements with a CSS class?

David

— David Ledger - Freelance Unix Sysadmin in the UK. HP-UX specialist of hpUG technical user group (www.hpug.org.uk) email@hidden www.ivdcs.co.uk

quote

Freeway user since 1997

http://www.walterdavisstudio.com

FreeCounter