0

I'm pretty new to jquery and I encountered a problem. I use $() to make a variable a jquery object. But somehow, it does not fully work as expected (I'd expect it can access to all jquery methods for that object). Here is what I did:

$(function() {
    var form = "<div id='menu-box'></div>";
    $(form).appendTo('body').css({'backgroundColor': 'blue'});  // this line works
    $(form).css({'backgroundColor': 'red'});  // this line does not.

});

I'm using jquery-1.9.1, is it a bug or I did something wrong.

1 Answer 1

2

Each time you write $(form), a new jQuery object is constructed that wraps the newly-created <div>. The second time this happens, you are operating on an element that has not been inserted into the DOM.

Consolidate the two usages instead to get the desired result (although of course this does not make sense for "real" code):

var $form = $("<div id='menu-box'></div>");
$form.appendTo('body').css({'backgroundColor': 'blue'});
$form.css({'backgroundColor': 'red'});
Sign up to request clarification or add additional context in comments.

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.