Creating CSS classes


Is it possible to create and delete CSS classes at runtime?


Yes. Just create the class as a string and set the style on the element. You can also get and save the elements previous style so you can restore it (or even modify it).

A bit more explanation:

The appearance of an element is defined by its style attribute. That’s a string of different properties, like

style = "top:100px; left:20px; color:red"

A class is a predefined style. It also contains a string of properties, but can be reused by multiple elements.

So, you could have a class called myButton, which is the styling you want to use for all your buttons. So, for each button, you have this:


If you change the contents of myButton, all your buttons will get the new style right away.

Of course, there is a lot more beyond this!

Thanks for your replies.

With jqxGrid, i am using the below method to colour cells which uses classes.

var cellclass = function(row, columnfield, value) {
if (value < 3) {
return ‘val3Class’;


and the val3Class is defined as below in project CSS:

.val3Class {
color: black !important;
background-color: #e83636 !important;

As classes must be used for jqxGrid for this case, and i cannot set the style attribute of the cell directly, if i want to change the background-colour from #e83636 to red, can this be done at runtime?

Thank you

First, enclose code in triple back ticks (```). It will make it more readable.

This seems to work for me - there may be a more elegant solution:

$("#row1Grid1 div[columnindex=1]")[0].style.backgroundColor="red"

Where Grid1 is the name of your grid.


For a single cell, your code works. But if i put it in a loop, it doesn’t.
I currently have 500 records in the grid, and the below loop should only colour the first 11 rows in the second column, but all rows get coloured.

   for     (t = (0); t  <= 10; t ++)
       $("#row" + t + "jqxgrid div[columnindex=1]")[0].style.backgroundColor="red"   

In your for loop initializer: Remove the () from around the zero; t less than 10 not less than or equal to.

I’ll bet you have a scrolling grid. The id’s change when you scroll it.

I am not an expert on jqxWidget - it’s not something we developed. You’ll need to look at their docs and maybe ask on their web board.

The () from around the zero in the loop analyzer was put there when i converted my app from Basic to Javascript. The grid still behaves the same when this is removed.

Yes, it is a scrolling grid and i see what you mean when scrolling the grid.

My problem is that i cannot create a class at runtime to colour each cell. I’ve tried other ways (cellsrenderer) to colour the cells that work but they have poor scrolling performance.
Using classes to colour cells is the fastest and works best, however, there doesn’t seem to be a way to create classes at runtime.