Sahil Sharma
Sahil Sharma

Reputation: 4217

jquery variable vs $(jquery varibale), what is difference b/w the two

When I do:

var x = $("#listing")

I get back html element with id listing,

And when I do $(x) or $($("#listing")), I get the same.

What is difference b/w two?

Upvotes: 1

Views: 1093

Answers (3)

BenM
BenM

Reputation: 53198

$() will convert something to a jQuery object (or collection). This is not the same as a Javascript variable.

When you store #listing in a variable such as var x = '#listing', you are simply passing a string to the jQuery constructor, which is then interpreted as a selector by Sizzle, jQuery's selector engine.

In the example provided, there is no difference between the two following lines:

var x = $('#listing');

var x = '#listing',
    $x = $(x);

In the first snippet, x is identical to $x in the second.

In the interest of completeness, the jQuery constructor can also accept a mixed type variable as its first parameter; it doesn't have to be a string. For example, it's possible to convert a DOMElement variable into a jQuery object using the following syntax:

var ele = document.getElementById('myItem'),
    $ele = $(ele);

Notice that $ele now has access to jQuery's own functions, such as addClass(), etc. Please see this demo.


Furthermore, passing a jQuery object to the constructor will simply return the same jQuery object. For example, given the following snippet:

var $x  = $('#listing'),
    $x2 = $( $x );

$x is identical to $x2.

Upvotes: 3

RaV
RaV

Reputation: 1048

Adding $ is creating jQuery object, its not normal variable. You can create jQuery object from DOM element, from another jQuery object or from normal javascript variable. Try to run console.log(x) console.log($(x)) and it will tell you all differences.

Upvotes: 0

Jordan Cauley
Jordan Cauley

Reputation: 353

Your x variable was made a jQuery object once it found the dorm item.

Once you run var x = $('#listing'); x has everything wrapping it has.

Thus you can run x.addClass('thing')

Upvotes: 0

Related Questions