1

Today I run into an interesting thing which I don't quite understand. This (see below) very simple jQuery script is not working, basically I want to change the background color of the prepended div to red if the blue == true (which is 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 I change this line:

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

to this:

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

the script works.

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

2 Answers 2

6

At the point when you lookup #panel, it does not exist in the DOM yet, therefore this line returns no objects:

var panelBg = $("#panel");

It works when you do $("#panel").css("background-color","red"); since this is executed after you've added the element with id=panel to the DOM.

Even if panelBg did work at the time you assign it, the panelBg and panel references would be pointing at the same elements anyway, so there doesn't seem to be any point to using two variables to point at the same thing.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, you are assigning an object that does not exist yet in the DOM to a variable.

You could move var panelBg = $("#panel"); to after you prepend your code.

As a side note, you could clean up your code a bit as well, instead of if (test == "true") you could have if (test)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.