0

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 commonly used Jquery object??\

Thanks!

6
  • it is fine jsfiddle.net/arunpjohny/YVYWP/1 Commented Aug 17, 2013 at 13:02
  • 5
    A null value? Did you somehow overwrite $, for example by loading Prototype.js? 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 to jQuery(). 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. Commented Aug 17, 2013 at 13:19
  • @KooiInc - I would say it's an empty jQuery object - jsfiddle.net/nabil_kadimi/YVYWP/4 Commented Aug 17, 2013 at 13:26

2 Answers 2

4

Your 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.

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

Comments

1

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.