Change element generated through the event of an already ready element

Asked

Viewed 35 times

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 the wipe button I get the following error:

Uncaught ReferenceError: bloco is not defined
  • 3

    That’s because your variable bloco is not set before you want to change the background color, What is this block? It corresponds to which element in HTML?

  • I guess instead of bloco.style.background = "white"; want to have $('.bloco').css('background', "white"); is that?

  • @Sergio Thank you so much, it solved my problem. I thought it was some different xD problem

  • @Raultomaz great! If you want you can mark the answer as accepted.

1 answer

1


That (s) element(s) you are adding <div class='bloco' ... can be selected through your class with jQuery using $('.bloco'). With jQuery, to change the .style is used .css(). So you can change that background exchanging:

bloco.style.background = "white";

for

$('.bloco').css('background', "white");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.