jQuery Tutorial: Selectors

By Xah Lee. Date:

This page is a tutorial on jQuery's selectors. If you don't know the basics, see: jQuery Basics Tutorial.

Getting Elements You Want

Here's a most basic example of getting a element and do something with it.

// make all paragraphs red

jQuery Selectors

Select by tag

// make all “p” tag elements red

Test yourself: jQuery Select By Tag Example

Select by ID

// make element of id “xyz” red

Test yourself: jQuery Select By ID Example

Select by Class Value

// make element of class “xyz” red

Test yourself: jQuery Select By Class Value Example

Select by Matching Any Attribute and Value

jq can select any tag attribute matching their value in many ways.

Attribute EqualsmyAttribName="myValue"
Attribute Not EqualmyAttribName!="myValue"
Attribute Starts WithmyAttribName^="myValue"
Attribute Ends WithmyAttribName$="myValue"
Attribute ContainsmyAttribName*="myValue"
Attribute Contains PrefixmyAttribName|="myValue"
Attribute Contains WordmyAttribName~="myValue"

Here's a example of getting all elements that has attribue “abc” with value “xyz”.

// select elements with attribute “abc” that has value “xyz”, make it red.

The syntax follows CSS's syntax. If you are not familiar with CSS seletor syntax, see: CSS Tag Matching (Selector) Syntax.

To get elements without using jQuery, see: DOM: Get Elements by ID, Tag, Name, Class, CSS Selector.

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. CSS
  3. JavaScript
  4. JS Obj Ref
  5. DOM
  6. SVG
  7. Blog