jgrant
jgrant

Reputation: 659

Getting or changing CSS class property with Javascript using DOM style

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;
    }
}

Upvotes: 49

Views: 276612

Answers (7)

RealNeo
RealNeo

Reputation: 470

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

Upvotes: 36

Johann Echavarria
Johann Echavarria

Reputation: 9945

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

Upvotes: 6

Pietro
Pietro

Reputation: 177

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>   

Upvotes: 0

Kingslayer47
Kingslayer47

Reputation: 493

If you are looking for sending color data from backend

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

Upvotes: -1

Shylo Hana
Shylo Hana

Reputation: 1870

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';
  }
}

Upvotes: 81

Jules Bartow
Jules Bartow

Reputation: 966

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>

Upvotes: 3

Infinity
Infinity

Reputation: 3875

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/

Upvotes: 4

Related Questions