Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My objective is to change the background color of a columns in a table without addressing each data entry individually by Id or Name. I know there are several ways to do this, and I've tried 3 to be exact, and I'm having problems with each. For the sake of simplicity and clarity, In this question, I'm asking how to successfully do it using the element.style.backgroundColor object in the DOM. Here's my HTML:

    <!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="tester.css">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
        <script type="text/javascript" src="tester.js"></script> 
    </head>
    <body>
    <button type="button" onClick="testerFunction()">Test</button>
        <table>
            <tr>
                <th class="col1">Column 1 Header</th>
                <th class="col2">Column 2 Header</th>
            </tr>
            <tr>
                <td class="col1">R1 C1</td>
                <td class="col2">R1 C2</td>
            </tr>
            <tr>
                <td class="col1">R2 C1</td>
                <td class="col2">R2 C2</td>
            </tr>
        </table>
     </body>
 </html>

My CSS file:

.col1{
    background-color:lime;  
}

And my Javascript file:

function testerFunction() {
    alert (document.getElementsByClassName('.col1').style.backgroundColor);  
}

When I run it I get roughly the same error in IE, Firefox, and Chrome:

cannot read property 'backgroundColor' of Undefined.

I have a feeling it has something to do with the data type returned by the document.getElementsByClassName DOM object. The referenced website says it returns an HTMLcollection. Other places I've found says it returns a "list" of elements. I tried making an array and assigning the result to the array and accessing each element in the array with a loop, but got the same error at the same place. It might be that I just don't know how to handle a, "collection." At any rate, I was expecting, "lime" or the hex or rgb equivalent because that's what I defined in the CSS file. I want to be able to change it with Javascript. Any help would be much appreciated. Thanks!

EDIT: Added arguments to Shylo Hana's Answer to make it more modular

function testerFunction() {
    changeColumnColor('col1','blue');
}
function changeColumnColor(column,color) {
    var cols = document.getElementsByClassName(column);
    for(i=0; i<cols.length; i++) {
      cols[i].style.backgroundColor = color;
    }
}
share|improve this question
 
check out this: api.jquery.com/css –  Mohsen Oct 14 '13 at 4:15
1  
@shylo's answer is correct, getElementsByClassName returns an array, which definitely has no "style" property –  xiaowl Oct 14 '13 at 4:30
add comment

3 Answers

up vote 3 down vote accepted

As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects. This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the elements...

function changeBGColor() {
  var cols =     document.getElementsByClassName('col1');
  for(i=0; i<cols.length; i++) {
    cols[i].style.backgroundColor =    'blue';
  }
}
share|improve this answer
 
This worked simply and beautifully. I added some arguments to make it more modular. Made it an edit to the post for formatting. –  jgrant Oct 14 '13 at 4:54
add comment

Maybe better document.querySelectorAll(".col1") because getElementsByClassName doesn't works in IE 8 and querySelectorAll does (althought CSS2 selectors only).

https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll

share|improve this answer
add comment

You don't need to add '.' in your class name. This will do

document.getElementsByClassName('col1')

Additionally, since you haven't define the background color via javascript, you won't able to call it directly. You have to use window.getComputedStyle() or jquery to achieve what you are trying to do above.

Here is a working example

http://jsfiddle.net/J9LU8/

share|improve this answer
 
Oh, sweet! It doesn't fix my major problem, but thanks! I'll change that and reference classes that way from now on. –  jgrant Oct 14 '13 at 4:13
 
Added a working jsfiddle so you can play around with it. –  Infinity Oct 14 '13 at 4:26
 
Thanks! jsfiddle and you are both awesome! –  jgrant Oct 14 '13 at 4:46
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.