Switch function to change the style of a variable? [closed]

1

How can I change the color of this variable? try everything; (

var segundo = ["1", "2", "3"]
var span;
        span = document.getElementById("span").innerHTML;
    switch (segundo) {
    case "1":
        {

            span.innerHTML.style = "cyan";
            break;
        }
    case "2":
        {
            span.innerHTML.style = "Red";
            break;
        }
    case "3":
        {
            span.innerHTML.style =  "Yellow";
            break;
        }


}
    
asked by Pachi 25.12.2017 в 05:09
source

3 answers

1

I do not know what you really want to do but you can not compare an array object with a value as the user said ftorres , you have to use indexes, I do not know what you really want to do, but usually in a switch you have a normal variable that is what you put in the condition of the switch and not necessarily an index of an array.

    var segundo = "1"; //Puedes sacar el valor de un input
    var span;
    span = document.getElementById("span").innerHTML;
    switch (segundo) {
        case "1":
            {
                span.innerHTML.style = "cyan";
                break;
            }
        case "2":
            {
                span.innerHTML.style = "Red";
                break;
            }
        case "3":
            {
                span.innerHTML.style =  "Yellow";
                break;
            }
    }
    
answered by 25.12.2017 в 10:53
0

You must use style.background to change the color of a div

var segundo = ["1", "2", "3"]
var span;
span = document.getElementById("span");
switch (segundo[0]) {
  case "1":
    {

      span.style.background = "cyan";
      break;
    }
  case "2":
    {
      span.style.background = "Red";
      break;
    }
  case "3":
    {
      span.style.background = "Yellow";
      break;
    }


}
#span {
  width: 100px;
  height: 100px;
}
<div id="span"></div>
    
answered by 25.12.2017 в 05:26
0

You are not specifying the property that changes the text color, but you are changing the value of the style object when it should be elemento.style.color . Change you can not change the text color of a innerHTML since it is of type String , not HTMLElement . You have to delete all references to innerHTML .

Here your code working:

var segundo = ["1", "2", "3"]
var span;
        span = document.getElementById("span");
    switch (segundo[0]) {
    case "1":
        {

            span.style.color = "cyan";
            break;
        }
    case "2":
        {
            span.style.color = "Red";
            break;
        }
    case "3":
        {
            span.style.color =  "Yellow";
            break;
        }


}
<span id="span">
  <span>Texto</span>
</span>
    
answered by 25.12.2017 в 12:26