Q:

Change the style of some elements in a loop

i have this navBar on top of layout page:
<div id="myTopnav" class="topnav" style="background-color: #030005; background-image: linear-gradient(#270133,#F5F5F5)">
            <a href="#" class="active ">@Session["UserName"].ToString() @Session["UserApe"].ToString()</a>
            <a href="#">Testing A</a>
            <a href="#">Testenado B</a>
            <a href="/Home/Logout">Cerrar Sesion</a>
            <a href="javascript:void(0);" class="icon" onclick="despMenu()"><i class="fa fa-bars"></i></a>
        </div>

The idea is to switch the gradient on each  button nad ofr that i have come to this:
window.addEventListener("load",inicializarEventos,false);
function inicializarEventos() {
    var ob1 = document.getElementById("myTopnav");
    var lista = ob1.getElementsByTagName("a");    
    var sw = 1;
    for (var i = 0; i < (lista.length - 1); i++) {
        if (sw == 1) {
            ob1.item(i).style.backgroundImage="linear-gradient(to top ,#270133,#F5F5F5)";            
            sw = 0;
            console.log("Entro a 1")
            break;
        }
        else {
            ob1.item(i).style.backgroundImage = "linear-gradient(to top ,#F5F5F5,#270133)";
            sw = 1;
            console.log("Entro a 2")
             }
      }
}

However it isnt working. What am i doing wrong? Is there a better way to do it?

A:

Your working rxample should look like: 
window.addEventListener("load",inicializarEventos,false);
function inicializarEventos() {
    var ob1 = document.getElementById("myTopnav");
    var lista = ob1.getElementsByTagName("a");    
    var sw = 1;
    for (var i = 0; i  < lista.length; i++) {
        if (sw == 1) {
            lista[i].style.backgroundImage="linear-gradient(to top ,#270133,#F5F5F5)";            
            sw = 0;
            console.log("Entro a 1")
            break;
        }
        else {
            lista[i].style.backgroundImage = "linear-gradient(to top ,#F5F5F5,#270133)";
            sw = 1;
            console.log("Entro a 2")
             }
      }
}

As mentioned above you should use lista[i] for accessing your current object and also you should check your entire list if there are no restrictions i  < lista.length

