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

JqueryJquery Selectors

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

: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 );
},

Solution 2 - Jquery

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/

Solution 3 - Jquery

The :input selector basically selects all form controls(input, textarea, select and button elements) where as input selector selects all the elements by tag name input.

Since radio button is a form element and also it uses input tag so they both can be used to select radio button. However both approaches differ the way they find the elements and thus each have different performance benefits.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMorten MertnerView Question on Stackoverflow
Solution 1 - JqueryDavid RuttkaView Answer on Stackoverflow
Solution 2 - JqueryYaron U.View Answer on Stackoverflow
Solution 3 - JqueryShankarSangoliView Answer on Stackoverflow