Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get background color of a css class applied to an element

Tags:

javascript

css

Say, I have the following CSS class:

.upComing{ background:#ccc; font-weight:bold; }

and in my HTML I have a table which some rows have that class applied, like so:

<table>
  <tr> <td></td> <td></td> </tr>
  <tr> <td></td> <td></td> </tr>
  <tr class='upComing'> <td></td> <td></td> </tr>
  <tr> <td></td> <td></td> </tr>
  <tr class='upComing'> <td></td> <td></td> </tr>
</table>

so far, so good, but via JavaScript I have events that listen on td clicks and I want to get the color of the row (I know I can get the class of the row, but in this case I need to be able to get the color from the class).

I need to do this because the table can be exported to an excel file and the row colors don't get applied on the excel file if they're on a CSS class, I want to apply this color to each td before sending the html to the excel generator.

PS: the table is dynamically generated from a jQuery plugin we created, it's still a work in progress, but when we feel confident enough with it we'll release it for the public.

--Update-- Here's an update on this topic, there's indeed a pure javascript solution for this, I had to take a dive into jQuery's source code to check this. Here's the solution:

1) point to the desired element

var tr = $("tr.upComing").first()[0]; 

2) get the COMPUTED STYLE of the element

var css = window.getComputedStyle( tr );

3) get the PROPERTY VALUE of the COMPUTED STYLE

var color = css.getPropertyValue( "background-color" );

As of this moment I've only tested in FF, Safari, Chromium and Opera on a Mac, if someone could try this on IE and give us feedback that'll be grand.

like image 421
Sam Ccp Avatar asked Dec 20 '12 20:12

Sam Ccp


1 Answers

You can use the jquery CSS method to get the background color from an element: http://api.jquery.com/css/

var color = $(this).css("background-color");
like image 83
MikeTedeschi Avatar answered Sep 21 '22 08:09

MikeTedeschi