Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of a leading colon in a jQuery selector?

I've starting using the Wijmo toolkit, and came across quite a few example selectors similar to this in their documentation pages:

$(":input[type='radio']").wijradio(); 

I'd have written mine like this:

$('input[type=radio]').wijradio(); 

Do these do the same or is there something I'm missing?

Note that there are two differences above: the first selector is prefixed with a colon and has quotes for the input type.

like image 861
Morten Mertner Avatar asked May 11 '12 13:05

Morten Mertner


People also ask

What is the use of colon in jQuery?

Note that there are two differences above: the first selector is prefixed with a colon and has quotes for the input type. One is the specialized :input selector, while the other is a generic Element selector.

Which symbol is used for selecting jQuery?

By default, jQuery uses "$" as a shortcut for "jQuery". Example :- $("#id") or jQuery("#id") both is same. $ sign is just a valid javascript identifier which is used as an alias for jQuery. Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function).

How jQuery selectors are executed?

If dealing with more than two selectors in a row then your last selectors are always executed first. For example, jQuery will first find all the elements with class “. list” and then it will select all the elements with the id “second”.


2 Answers

:input is a jQuery extension while input is a CSS selector.

textarea, button, and select elements would be matched by the former, but not the latter.

The latter is faster, so use it for your specific radio example. Use :input when you want "all form elements" even if they aren't strictly <input> tags. Even in that case, the recommendation is to use a standard CSS selector first, then use .filter(':input') on that set.

Because :input is a jQuery extension and not part of the CSS specification, queries using :input cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :input to select elements, first select the elements using a pure CSS selector, then use .filter(":input").

In the 1.7.2 source, the :input filter tests a regular expression against the nodeName:

input: function( elem ) {             return (/input|select|textarea|button/i).test( elem.nodeName ); }, 
like image 78
David Ruttka Avatar answered Sep 20 '22 01:09

David Ruttka


the $("input") selector will choose only elements of the type input

while the $(":input") selector will catch all the inputs elements (such as textarea, select, input etc...)

for further information, go the jQuery official documentation about the :input selector at:

http://api.jquery.com/input-selector/

like image 45
Yaron U. Avatar answered Sep 23 '22 01:09

Yaron U.