Simple script not working with .prepend() and .css() methods in jQuery -


today run interesting thing don't quite understand. (see below) simple jquery script not working, want change background color of prepended div red if blue == true (which true).

var panel = $("<div id='panel'></div>"); var panelbg = $("#panel");  var test = "true"; var red  = "true"; var blue = "true";   if (test == "true") {       if (red == "true") {         $("#first").prepend(panel);      }        if (blue == "true") {         panelbg.css("background-color","red");      }   } 

but when change line:

  panelbg.css("background-color","red"); 

to this:

  $("#panel").css("background-color","red"); 

the script works.

working demo: http://jsfiddle.net/wk2jw/

at point when lookup #panel, not exist in dom yet, therefore line returns no objects:

var panelbg = $("#panel"); 

it works when $("#panel").css("background-color","red"); since executed after you've added element id=panel dom.

even if panelbg did work @ time assign it, panelbg , panel references pointing @ same elements anyway, there doesn't seem point using 2 variables point @ same thing.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -