Understanding Basic jQuery Selectors

Oct 24, 2014


In this post we will start looking at the basic jQuery selectors. If you are new to jQuery, please referent to my previous post on Understanding jQuery.

In this blog post we will explore following main jQuery selectors.

  • Element Selector
  • ID Selector
  • Class Selector

For our examples we will be working with the sample created at the jsFiddle web site. Following is the link to the public fiddle implementing all the samples we are discussing as part of this blog.

jQuery Element Selector

As the name suggests, when you want to select a particular HTML element/ or set of elements by it's type your choice of jQuery selector should be Element selector. For example, selecting all the Div on the page(And hiding them and possibly show them back!!).

Element Selector

The syntax for jQuery Element Selector is $('Element Name You Want To Select')

jQuery ID Selector

If you want to select an element using it's ID, you can use the jQuery Element selector. In this example, hiding and showing the Element who has the ID "dvTwo".

ID Selector

The syntax for jQuery Element Selector is $('#ID Of The Target Element')

The important thing to remember is the # in front of the Element ID.

jQuery Class Selector

And let's say you want to select all the elements who have a specific CSS class attached to them. For example finding all the elements who have css class set to infoDiv, we want to change their border style.

Class Selector

The syntax for jQuery Element Selector is $('.ID Of The Target Element')

The important thing to remember is the ., (The Dot) in front of the target class.

If you know little bit about CSS, you must have realized that the jQuery selectors are nothing new. In reality, they are using the existing CSS selectors. So the way you can have custom CSS selector for your style, same custom selector can be placed into your jQuery selector code and things will just work.

Word About Actions On Selected Elements

When you are using a jQuery to select Element(s) form your DOM, your intention is to do something with them, for example show/hide/change color etc. These things are know as action. And I explained in my previous article, these part of the JavaScript is actions that you need to perform on the result of your selectors.

Some of the usages could be,

  • Show/Hide Element (Which we did in the above
  • Add/Remove Borders & Background Colors
  • Add/Remove CSS classes
  • In case of CheckBox/RadioButton, selecting/deselecting them

and many more. In next few blog posts I will show you examples of performing some basic actions to your DOM elements.