user2864466
user2864466

Reputation: 41

jQuery $.method() vs $(selector).method()

I'm having a hard time understanding the difference between $.method() and $(selector).method for jQuery.

What elements in the DOM does the $.method() actually apply for? If anyone could help explain the difference between the two statements, it would be highly appreciated!

Upvotes: 2

Views: 200

Answers (4)

Exception
Exception

Reputation: 8389

The one liner is, either you want to get the input also for you and apply method on it or you have input and want to apply jQuery method on it. This question is very broad.

Upvotes: -1

nietonfir
nietonfir

Reputation: 4881

$.function() are helper functions that you can use however you like. Some of these are obsolete since a lot have been added to the object prototypes (e.g. Array.forEach()), like $.each(). The official documentation describes $.each() as

Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.

while .each() iterates over a jQuery object and executes the callback on every matched element.

In a nutshell: functions that apply to jQuery objects work on/with those while the others are helper functions.

Upvotes: 1

MacMac
MacMac

Reputation: 35361

A $() requires a selector to grab the element and return that into a chain. While $. is an ordinary method that can be used that isn't chained of the DOM element.

Take this for example:

// Will trim the current string - returns string
$.trim(' string ')

// Returns the current element in the DOM ready for chaining, i.e. $().remove
$('#id') 

Upvotes: 3

alex
alex

Reputation: 490647

The methods assigned to the jQuery object directly don't apply to any collection: they're utility methods (that's why they're assigned there).

For example, look at $.each() and $.noConflict().

Upvotes: 1

Related Questions