Change element generated through the event of an element already ready

0

I have the following HTML code:

    <div class="header">
        <ul class="navigation">
           <li><a>Home</a></li>
           <li><a id="limpar">Limpar</a></li>
        </ul>
    </div>

    <div class="centro">

    </div>

And javascript:

$(window).load(function() {
   for (i = 1; i <= 2000; i++) 
   {
       $('.centro').append("<div class='bloco' onclick='changeColor(this)'> </div>");
   }
})

function changeColor(x) {
  if(x.style.background == "purple")
  {
     x.style.background = "white";
     x.style.color = "black";
  }
  else
  {
     x.style.background = "purple";
     x.style.color = "white";
  }
}

$(document).ready(function() {  
   $("#limpar").click(function(){
      bloco.style.background = "white";
   });
});

When I click on the clean button I get the following error:

Uncaught ReferenceError: bloco is not defined
    
asked by anonymous 14.08.2016 / 18:43

1 answer

1

The element (s) you are adding <div class='bloco' ... can be selected through your jQuery class using $('.bloco') . With jQuery, to change the .style it uses .css() . So you can change this background by changing:

bloco.style.background = "white";

by

$('.bloco').css('background', "white");
    
14.08.2016 / 19:26