50

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;
    }
}
2
  • check out this: api.jquery.com/css Commented Oct 14, 2013 at 4:15
  • 1
    @shylo's answer is correct, getElementsByClassName returns an array, which definitely has no "style" property Commented Oct 14, 2013 at 4:30

7 Answers 7

81

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 array elements...

function changeBGColor() {
  var cols = document.getElementsByClassName('col1');
  for(i = 0; i < cols.length; i++) {
    cols[i].style.backgroundColor = 'blue';
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked simply and beautifully. I added some arguments to make it more modular. Made it an edit to the post for formatting.
36

I think this is not the best way, but in my case other methods did not work.

stylesheet = document.styleSheets[0]
stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);

Example from https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

1 Comment

This really helped me a lot. This is really good for what I'm doing and I learned something new. Thank you.
6

Maybe better document.querySelectorAll(".col1") because getElementsByClassName doesn't work 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

Comments

4

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/

2 Comments

Oh, sweet! It doesn't fix my major problem, but thanks! I'll change that and reference classes that way from now on.
Thanks! jsfiddle and you are both awesome!
3

Nice. Thank you. Worked For Me.

Not sure why you loaded jQuery though. It's not used. Some of us still use dial up modems and satellite with bandwidth limitations. Less is more betterer.

<script>
        function showAnswers(){
          var cols = document.getElementsByClassName('Answer');
          for(i=0; i<cols.length; i++) {
            cols[i].style.backgroundColor = 'lime';
            cols[i].style.width = '50%';
            cols[i].style.borderRadius = '6px';         
            cols[i].style.padding = '10px';
            cols[i].style.border = '1px green solid';
            }
        }
        function hideAnswers(){
          var cols = document.getElementsByClassName('Answer');
          for(i=0; i<cols.length; i++) {
            cols[i].style.backgroundColor = 'transparent';
            cols[i].style.width = 'inheret';
            cols[i].style.borderRadius = '0';
            cols[i].style.padding = '0';
            cols[i].style.border = 'none';          
          }
        }
    </script>

Comments

0

very useful to change colors to tab buttons according to the one that is pressed. I integrated with this word

<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css'>
        
        
<button class='btn btn-secondary' onclick='myFunction2(this,"red");openCity("Rome")' style="background-color: red;"><strong>ROME</strong></button> 
<button class='btn btn-secondary' onclick='myFunction2(this,"red");openCity("Berlin")'><strong>BERLIN</strong></button>
    
<div id='Rome' class='city' >Welcome to Rome</div>
<div id='Berlin' class='city' >Welcome to Berlin</div>
        
     <script>   
        function openCity(cityName) {
            var i;
            var x = document.getElementsByClassName('city');
            for (i = 0; i < x.length; i++) {
              x[i].style.display = 'none';
            }
            document.getElementById(cityName).style.display = 'block';
          }
        
          function myFunction2(elmnt,clr) {
          var classes = document.getElementsByClassName('btn-secondary');
          for(i = 0; i < classes.length; i++) {
            classes[i].style.backgroundColor = 'grey';
          }
          elmnt.style.backgroundColor = clr;
          }
        </script>   

Comments

-1

If you are looking for sending color data from backend

def color():
    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
    return color

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.