I am new to Jquery and javascript.
While I was writing a javascript code, I found myself using a particular jquery object often, so I declared a variable for it. For example,
$(document).ready(function() {
var object_list = $("#object_list");
/*Do something with the variable*/
alert(object_list);
object_list.hide();
});
However, this doesn't seem to work ("alert(object_list)" gives me a null value).
Is declaring a variable like this wrong in jquery???
If so, then what is the right way so that I can refer to monly used Jquery object??\
Thanks!
I am new to Jquery and javascript.
While I was writing a javascript code, I found myself using a particular jquery object often, so I declared a variable for it. For example,
$(document).ready(function() {
var object_list = $("#object_list");
/*Do something with the variable*/
alert(object_list);
object_list.hide();
});
However, this doesn't seem to work ("alert(object_list)" gives me a null value).
Is declaring a variable like this wrong in jquery???
If so, then what is the right way so that I can refer to monly used Jquery object??\
Thanks!
Share Improve this question asked Aug 17, 2013 at 12:59 user2492270user2492270 2,2956 gold badges44 silver badges56 bronze badges 6- it is fine jsfiddle/arunpjohny/YVYWP/1 – Arun P Johny Commented Aug 17, 2013 at 13:02
-
5
A
null
value? Did you somehow overwrite$
, for example by loading Prototype.js? – Bergi Commented Aug 17, 2013 at 13:03 -
@Bergi I join my voice to you, the alert should show an Object even if the selector doesn't much anything, so yes, good point,
$()
here is not an alias tojQuery()
. – Nabil Kadimi Commented Aug 17, 2013 at 13:09 -
@NabilKadimi as a matter of fact, it should return an
Array
, empty or containing one or more HtmlElement objects. – KooiInc Commented Aug 17, 2013 at 13:19 - @KooiInc - I would say it's an empty jQuery object - jsfiddle/nabil_kadimi/YVYWP/4 – Nabil Kadimi Commented Aug 17, 2013 at 13:26
2 Answers
Reset to default 4Your jQuery is probably working in noConflict mode, which means that you detached the alias $ = jQuery
somewhere earlier in your code. WordPress for example does that (see latest line of wp-includes/js/jquery.js).
Use this code instead:
jQuery(document).ready(function($) {
var object_list = $("#object_list");
/*Do something with the variable*/
alert(object_list);
object_list.hide();
});
What you are doing is aliasing the jQuery object within the .ready
method, see the section for Aliasing the jQuery Namespace in the .ready() method documentation.
You could wrap your code inside an immediate function to avoid naming collision with $
. This technique is useful when you already have a lot of code using the $
and refactoring to change the name may be error-prone.
(function($){
$(document).ready(function() {
var object_list = $("#object_list");
/*Do something with the variable*/
alert(object_list);
object_list.hide();
});
})(jQuery);