casca casca - 6 months ago 11
CSS Question

Swap background-color of a specific div with switch/case

I'm trying to swap the background-color of some specific divs basing on their content.

Their background-color should swap when their input is like "Lifestyle" or "Politics" or "Economy" or "Local" or "Sports" or "News".

var colorInput = document.getElementById('views-field-field-section').textContent;

switch (colorInput) {
case 'Lifestyle':
document.getElementById('views-field-field-section').style.backgroundColor = '#9518b8';
break;
case 'Local':
document.getElementById('views-field-field-section').style.backgroundColor = '#009fe3';
break;
case 'Sports':
document.getElementById('views-field-field-section').style.backgroundColor = '#95c11f';
break;
case 'Economy':
document.getElementById('views-field-field-section').style.backgroundColor = '#d40d10';
break;
case: 'Politics':
document.getElementById('views-field-field-section').style.backgroundColor = '#ffcc00';
break;
default:

break;
}


http://jsfiddle.net/gFN6r/501/

Answer

You cannot use ids more than once in an html document. This would be invalid html. I have changed the id to a class, and then used the following code and it works:

var colorInput = document.getElementsByClassName('views-field-field-section');
for(i=0; i<colorInput.length; i++) {
      var colorInputText = colorInput[i].textContent.trim();
      switch (colorInputText) {
        case 'Lifestyle':
                colorInput[i].style.backgroundColor = '#9518b8';                
                break;
        case 'Local':
                colorInput[i].style.backgroundColor = '#009fe3';
                break;
        case 'Sports':
                colorInput[i].style.backgroundColor = '#95c11f';
                break;
        case 'Economy':
                colorInput[i].style.backgroundColor = '#d40d10';
                break;
        case 'Politics':
                colorInput[i].style.backgroundColor = '#ffcc00';
                break;
        default:
                text ='Nix!'; 
  }
}

Here is the jsfiddle: http://jsfiddle.net/gFN6r/505/