When I store a jQuery object in a variable, like this:
var $myObject = $("div#comments");
…I can’t use the object $myObject!
This is what I’m doing to change the html of div#comments:
$myObject.html(data);
It does nothing. I already tried this way too, this time to select an element inside div#comments:
$("div.comment", $myObject);
It doesn’t work.
I just want to be able to save an element in a variable and then use it!
Note: some people don’t put $ before the variable name, like this: myObject.
Are you calling it after the document is loaded?
(This is a shortcut for jQuery’s
.ready()method.)As long as the document is loaded, and you have a
<div>with the IDcommentson the page when it loads, it should work.Also remember that there can only be one element on the page with any given ID. Because of this, it is actually a little better (quicker) to do
$("#comments");instead of$("div#comments");.