css is not a function

2

I have an array of items that I want to change the css in scroll of my Document, when I give console.log() , the items are there, but in the loop to change their style, it gives me the message:

  

Uncaught TypeError: itemsmenu [i] .css is not a function

Event call Scroll :

 $(document).scroll(function(){
       var brand  = $('#brand');
       var posicao = window.pageYOffset;
       var navbar = $('#navbar');
       var itensmenu = $(".nav-item");
       var topo = $("#topo");
       trocaNav(navbar, topo, posicao, brand, itensmenu);

    });

Loop:

function trocaNav(navbar, topo, posicao, brand, itensmenu){
  if (posicao == 0){
    navbar.css("background-color", "transparent");
    brand.attr("src","img/logo_BP.png");
  } else{
    navbar.css("background-color", "white");
    brand.attr("src","img/logo.png");
  }

  for(var i = 0; i < itensmenu.length; i++){
    if (posicao == 0) {
      itensmenu[i].css("background-color", "white");
      itensmenu[i].css("color" , "white" );
    } else{
      itensmenu[i].css("background-color", "black");
      itensmenu[i].css("color", "black");         
    }
  }

}
    
asked by anonymous 06.04.2017 / 17:31

1 answer

5

The use of [index] in jQuery DOM only works to get the first item, since it is a "shortcut", to get other items should use either .each or .eq

Do this:

  

.eq returns the jQuery object and .get returns the DOM element

  for(var i = 0; i < itensmenu.length; i++){
    var current = itensmenu.eq(i);

    if (posicao == 0) {
      current.css("background-color", "white");
      current.css("color" , "white" );
    } else{
      current.css("background-color", "black");
      current.css("color", "black");         
    }
  }

Or rather it would look like this:

var bg = "white", cor = "white";

if (posicao == 0) {
    bg = "black";
    cor = "black";
}

for(var i = 0; i < itensmenu.length; i++){
  var current = itensmenu.eq(i);

  current.css("background-color", bg);
  current.css("color", cor);
}

Or so, with .each :

var bg = "white", cor = "white";

if (posicao == 0) {
    bg = "black";
    cor = "black";
}

itensmenu.each(function (i) {
  $(this).css({
      "background-color": bg,
      "color": cor
  });
});
    
06.04.2017 / 17:34