jQuery selector | How Selector in jquery works by CSS ID, name, class and more

jQuery selector

The most important purpose of jquery is: select elements and do some action on those selected elements. The jquery element selectors allows you to search or select HTML elements (CSS3 as well as custom selectors) and then do intended action on that.

For example we see Show/Hide feature on many sites for certain features of the page. This can be done by using jquery selector. We can code all HTML of show or hide part in particular class e.g. “.showmenu” class. When Show is clicked menu would be shown and vice versa.

Syntax of using jquery element selector

Selectors in jquery start with: $()

For example: $(‘tagname’) , $(“#ID”) $(“.class”)

This chapter explains very important jquery selectors one by one below with an example. Note that for examples below we have placed juqery library at jquery folder, where html file is placed.

Selecting on the basis of element ID

$(“#ID_of_Element”);

The ID will be represented by “#” followed by ID of the element that should be unique in document. In your HTML your paragraphs, form buttons, Div etc. can be ID based. The jquery selector will search for given id in document and perform given action.

Example of Selector by #ID

In example below, Div with id=text will be show and Show button is made hidden when document is ready. As you click on “Hide text” button div will be hidden and “Show text” button will be shown.



Selecting elements by class name

$(“.classname”);

Selecting elements by class names requires calling by ‘.’ (period) followed by class name of the element. The jquery selector will search for given class in document and perform given action.

Example of Selector by .Class name

In example below, Div with class=text will be shown and Show button is made hidden when document is ready. As you click on “Hide text” button div will be hidden and “Show text” button will be shown.



In real time development, your class name specifications may be specified in an outer CSS file.

Selecting elements by name

$(‘html_tag_name’);

Where html tag name can be p, div, img etc. like

$(‘p’) – select all element with name p in page

$(‘div’) = select all elements with name div in page

Example of Selector by tag name

Same example as given above with except that we used tag name div to hide and show text in jquery selector rather class name. If you have multiple div tags in page it will show/hide all Divs.



Also see jquery class selector |


Was this article helpful?

Related Articles

Leave A Comment?