petko_stankoski
petko_stankoski

Reputation: 10713

Jquery syntax meaning - difference between $(x) and x

I know that when we have an element with id='someId', we can access it with Jquery like this:

$('#someId')

But sometimes when we have a variable:

var x;

We use just x or $(x).

When do we use $(x) instead of x? When do we use $($(x)) instead of x?

Upvotes: 0

Views: 443

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318488

$(x) creates a jQuery object containing x (which should be a DOM node) or the elements contained in x (if it's an array or jQuery object).

You use x if you just want the plain DOM object (assuming x is one), e.g. x.id to get the element's ID as there is no need to create a jQuery object for that - it would be even more to write: $(x).prop('id').

You never use $($(x))! There is just no reason to do that ever. While it works it is just like $(x) except the fact that you first create a jQuery object and then put the contents of that jQuery object into a new jQuery object.


If you need the other way (jQuery object => DOM object) there are quite a few ways. y[0] is the easiest way to get the first element; use y.get() if you want an array with all elements contained in the jQuery object y.

Upvotes: 4

Related Questions