Reputation: 1162
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.
Upvotes: 8
Views: 19592
Reputation: 31
If it helps, I have had the same problem and found out, that in your case using:
a = document.getElementsByClassName('upcoming');
console.log(a.style.backgroundColor);
would work IF you do not use:
document.addEventListener("DOMContentLoaded", function(event) {});<
but instead refer to the js file just before the closing body tag, which is considered dirty though.
Upvotes: 1
Reputation: 583
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");
Upvotes: 8
Reputation: 4798
The following should do it
$('.upComing:eq(0)').css('backgroundColor')
Upvotes: 2