Forum Moderators: open

Message Too Old, No Replies

Query on getElementsByTagName.

Question

         

PhoenixMan

4:55 am on Nov 26, 2004 (gmt 0)

10+ Year Member



I'm working on a script that changes the color of the text, background, headings, and horizontal rules upon the user's entering the rgb or hexadecimal value code into an input box. To facilitate this, I needed to find an easy way to access classes assigned to various elements.

My question is whether or not the following is a valid statement, referring to a P tag with the class value of "blue" and the style associated with it. If it isn't, can someone tell me a better/easier/correct way of accessing it? For reference, I have various P tags with different classes, so I can't just reference all of the P tags at once.:

document.getElementsByTagName("p").className.blue.style

Bernard Marx

3:23 pm on Nov 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Valid? No it's not, unfortunately.

This (or a variation) is a common question. You have two main options:

1. Get a reference to the style rule at source (in the stylesheet), and apply the change to the rule's style object.

2. Collect all the P's in the usual way, then loop through them, finding the ones that have a class attribute containing that name. I say "containing" because an element may have multiple classNames.

The two options aren't equivalent, since #2 will change the style property of elements themselves, which have a much higher priority than class specs. If you a creating something that is meant to emulate exactly a written change in the class spec, then use #1.