Brienne Schroth
Brienne Schroth

Reputation: 2457

How do I access the individual styles of a CSS rule-set using JavaScript?

If I have a style defined using a class selector:

.example {
width: 50px;
}

And in JavaScript, I would like to get the value of the width property for that rule-set, without using some reference to a concrete element that uses that rule-set. I want something which would give me the output "50" or "50px" given the input of "example" and "width".

Upvotes: 2

Views: 198

Answers (3)

Ryan Lynch
Ryan Lynch

Reputation: 7776

See this entry on using document.styleSheets to access CSS rules on Quirksmode.

EDIT: I do agree with others here though in that if this is an important requirement you'll have a much easier time of it if you leverage one of the mentioned libraries.

Upvotes: 1

Quentin
Quentin

Reputation: 943165

This is one of those times when I do recommend the use of a library.

There are a couple of different methods to access stylesheets attached to a document, and different browsers support different ones.

The YUI 2 StyleSheet Utility will smooth out the differences for you, although you would have to search through the rules to find the one that you were looking for.

Upvotes: 0

Nosredna
Nosredna

Reputation: 86196

I can't think of a way to do it without creating an element that uses that class. I'd create an invisible div with the class and query that div.

Upvotes: 0

Related Questions