Skip to content

Instantly share code, notes, and snippets.

@wescosta
Last active September 29, 2015 14:44
Show Gist options
  • Save wescosta/65da89c3dc4068f3f37a to your computer and use it in GitHub Desktop.
Save wescosta/65da89c3dc4068f3f37a to your computer and use it in GitHub Desktop.

#Selectors

Selectors are the heart of jQuery. They were borrowed from CSS selectors, though. Then jQuery added its bits to it. It is very simple to find elements in the page by class, attributes, type, content, state, etc. You must have a good understanding on selector in order to write good code with jQuery. Combining selectors can help you to find the very specific element your code is looking for. So feel free to mix and mathc and test these out.

For full reference on selectors, visti the following links:

JQuery Selector API CSS Selector Reference

##Simple selectors Some simple code using jQuery selector

###by id Returns only one element. You should not have more than one element with the same id in the page.

$('#id')
$('#my-div')

###by tag name

$('div')
$('input')

//some html5 tags :)
$('main')
$('nav')
$('section')
$('aside')

###by class

$('.login-form')
$('.btn')
$('.my-special-class')

###by attributes

$('input[name=email]')
$('input[type=button]')
$('div[data-toogle=on]')

###by type

$('input:button') //equivalent to $('input[type=button]')
$('input:checkbox') //equivalent to $('input[type=checkbox]')

$(':header') //selects all elements that are headers, like h1, h2, h3 and so on
$(':file') //selects all elements of type file

###by content These are jQuery extension and not part of the CSS specification. More on

$('div:contains("John")')
$('ul').has('li') //use like this $('your-pure-css-selector').has(selector/DOMElement)

###by visibility Note: These are jQuery extensions and not part of the CSS specification

$('.list:visible') //selects a visible element with the .list class
$('.list:hidden') //selects a hidden element with the .list class

###by state A few different ways to select disabled buttons

$('.btn:disabled')
$('input:button:disabled')
$('[type=button]:disabled')

You can do the same for enabled, checked, focus and even combine multiple states in any order (try an order which makes sense when you read it)

$('.btn:enabled')
$('input:focus') //selects the input element which has focus

$('input:valid') //selects all input elements with an valid value
$('input:invalid') //selects all input elements with an invalid value

//selects checked, enabled and visible checkboxes
$('input:checked:enabled:visible:checkbox')

//selects checked, disabled and visible radio buttons
$('input:checked:disabled:visible:radio')

Note: enabled, checked, valid, invalid, otional and required are some pure, handy CSS3 pseudo selectors, which jQuery borrows.

##Advanced Selectors

###Attributes

####contains [attribute~=value] CSS2 selector that selects elements with an attribute with a value containing a given word, delimited by spaces. The word has to match as whole. Partial values are not supported.

//consider that a form has an input like this
<input type="text" placeholder="some-placeholder-text">​

//this selector does not select that input
$('[placeholder~=some]')

//this on does
$('[placeholder~=some-placeholder-text]')

####contains (partial value) [attribute*=value] Different from the previous selector, this one does support partial values. This is a CSS3 selector. (Good improvement ha!)

//consider that a form has inputs like these
<input type="text" placeholder="placeholder-text"><input type="text" placeholder="some-placeholder-text"><input type="text" placeholder="some-placeholder">​

//each of these selectors select all those inputs
$('[placeholder*=some]')
$('[placeholder*=holder]')
$('[placeholder*=text]')

####begins with [attribute^=value] a[href^="https"] Selects every element whose href attribute value begins with "https"

Similiar to what we saw with the contains, this is a CSS3 selector which is an improvement on a similiar one from CSS2 [attribute|=value]

####ends with [attribute$=value] a[href$=".pdf"] Selects every element whose href attribute value ends with ".pdf"

####not equal [name!=value] Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value

##Multiple Selectors

As mentioned you can mix selector to find a very specific element. That also brings performance benefits, since a more specific selector performs better than a too general one, which may need to be filtered later on.

//selects enabled input type button with the class .btn inside the main container
$('main input[type=button].btn:enabled')

//selects enabled, invalid inputs in the .contact-form
$('.contact-form input:enabled:invalid')

##find and filter functions Jquery has also a find and filter function which expects a seletor as a parameter. It's common to use find() in order to find elements inside a container, a div for example. Whereas, filter() is commonly used the filter the results of a previous selection. Both will be further covered in the traversing chapter.

##Performance There are selectors which are NOT part of the the CSS specification, but a jQuery extension instead, such as visible, hidden, button, submit, checkbox, etc. When using them, it is recommended to firt select elements with a pure CSS selector then filter the results using the jQuery's extension you want to. Thus the code will take advantage of the performance boost provided by the native DOM querySelectorAll() method.

For example:

//:hidden is a jQuery extension and not part of the CSS specification
$('form input:enabled').filter('checkbox:hidden')

Check out the list of jQuery selector extensions

##Native Query Selector Bear in mind that modern browsers already provide a selector API. That means, if you are not supporting old browsers, you should not need jQuery only to use its selector api. If that is the case, it's recommended to use the browser's native query selector api. It does not support all jquery selector does, though.

//selects the first input in the page
document.querySelector('input')

//selects the all enabled inputs in a form
document.querySelectorAll('form input:enabled')

Check out more on these links:

querySelector querySelectorAll

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment