Iucounu
Iucounu

Reputation: 1660

How to test for existence of CSS class in JavaScript without jQuery?

I am writing a reusable .NET / Sitecore control which spits out some HTML elements with certain CSS classes. I'd like to provide a default set of CSS definitions for those classes, but only if nothing else in the page load has done so--this is to allow for default formatting but for this to be overridden outside the control.

Is there a reliable cross-browser way, preferably without jQuery, to sense in JavaScript whether there's a pre-existing CSS class definition?

Upvotes: 0

Views: 698

Answers (2)

IvanL
IvanL

Reputation: 2485

I do not really understand why you'd only want to supply your defaults when there's nothing else... CSS itself basically words your requirement almost: "Cascading". You just need to make sure that your defaults are defined all the way on top (all the time) and that any custom styling follows afterwards. Especially if you are using CSS classes and your selectors use these classnames (because CSS of course has certain rules where a more specific defined declaration will take prio over a less specific one even when the first came before the latter).

The only reason I see to attempt your requirement is when you're concerned about every single bit you're sending towards the client. In that case javascript isn't exactly the answer as you need to determine this server side (instead of sending complex detection scripts towards the client which may be as large as your default styling...).

So I would reconsider your requirement before threading onto javascript detection of styling.

Upvotes: -1

Roman Klimenko
Roman Klimenko

Reputation: 1337

You have to look at document.styleSheets

Upvotes: 3

Related Questions