0

I have, for example, this CSS rules:

<style>
table {background:red;}
div {background:green;}
</style>

and the following HTML, calling a JS function:

<table onclick="turnItsCSS(on/off)"><tr><td>123</td></tr></table>

Is it possible for turnItsCSS() to toggle CSS rules for tables?

All I figured is to parse innerHTML in document head, but it doesn't seem to be sufficient.

el Dude
  • 5,003
  • 5
  • 28
  • 40

4 Answers4

0

In jQuery you can use the .addClass() or .removeClass() (or more simply, the .toggleClass() function)

So, say you have a table:

<a href="#" id="addClass">Add CSS</a>
<table id="the_table">
    <tr>
        <td>Hello, World</td>
    </tr>
</table>

And you have the following CSS:

.table_red {
    color: red;
}

In your jQuery, you could have:

$("#addClass").click(function() {
    $("#the_table").addClass(".table_red");

    // Check if the class is active, and remove it for a toggle.
    // or use the .toggleClass() function.
});
Dennis
  • 32,200
  • 11
  • 64
  • 79
Julio
  • 2,261
  • 4
  • 30
  • 56
0

This is a nice way to switching between css files:

<button onclick="$('[rel=stylesheet]').attr('href','http://www.example.com/css/menu_red.css')">red</button>

<button onclick="$('[rel=stylesheet]').attr('href','http://www.example.com/css/menu_black.css')">black</button>
Code.Town
  • 1,216
  • 10
  • 16
0

you can use jQuery or JavaScript to change dynamically your objects style in JavaScript you can get element by id or class name and set style

var obj = getElementById("idName");
obj.style.width = "300px";

or

var obj = getElementsByClassName("classname")[0]; //return array with with all elements with same class
obj.style.width = "300px";
ser savv
  • 21
  • 1
  • 2
0

Here's an example using HTML5, unfortunately i don't think it's supported in < IE10.

HTML

<table onclick="this.classList.toggle('on');"><tr><td>123</td></tr></table>

CSS

.on { 
    background-color:red;
}

http://jsfiddle.net/sGKgV/

Check out https://stackoverflow.com/a/196038/1156119 for a thorough rundown of other techniques.

Community
  • 1
  • 1
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166