1

I'm developing a web based source code editor. I'm thinking of adding support for themes (syntax highlighting).

//Default theme
.default-reserved-word
{
  background-color : red;
}

//Some other theme
.monokai-reserved-word
{
  background-color : green;
}

inside the editor each syntax highlightable word is surrounded by a span tag with the appropriate class:

....
<span class="default-reserved-word">def</span>method name
...

which I want to convert to (when the user clicks a "change theme" button)

....
<span class="monokai-reserved-word">def</span>method name
...

Is there a simple way of switching these CSS rules without going through all the elements and modifying the class attributes?

(FWIW, I need to support IE7+, FF3.6+)

3
  • 1
    Rather than switching the class names, I would load in a new stylesheet for each theme. Commented Aug 2, 2011 at 8:50
  • You can do this (rather tediously) using plain old Javascript, though I'd suggest a framework such as jQuery because it will make the process much simpler and faster. Commented Aug 2, 2011 at 8:52
  • @huhucat Don't forget to accept answers (not just for this question) if your question has been sufficiently answered. Commented Aug 2, 2011 at 9:18

3 Answers 3

4

I'd suggest using a different method, perhaps have a theme class on a higher parent container:

<div class="theme-default">

And then use CSS like this:

.theme-default .reserved-word {
    color: blue;
}

Whilst this method is not exactly what you've asked for it will simplify the process of changing styles, for a start you won't have to search through loads of spans, finding the current class of theme-name + ' -reserved-word' (etc) and doing a string replace on them.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 I really like this method and it is a technique that is simple and at the same time clever.
Wow, this is pretty slick! Thank you! :)
0

Add a class name to the root element (<html>) and change that on use input.

.theme1 .reserved-word { color: red; }
.theme2 .reserved-word { color: green; }

and then change

<html class="theme1">

to

<html class="theme2">

with Javascript.

Comments

-2

You can use jQuery for that:

var elements = $('.default-reserved-word')
elements.removeClass('default-reserved-word');
elements.addClass('monokai-reserved-word');

2 Comments

Changing all elements' classes is unneeded and inefficient. Instead, you can change a higher parent's classname and declare the CSS accordingly ;)
I guess I was replying too literally to his question. I sure got my share of -1s for that :D Swapping the CSS file would indeed be a much better solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.