jQuery Selector examples

jQuery selectors are important part of jQuery. It is used to select DOM elements and manipulate it.

Syntax:
It should start with $ followed by parenthesis.
For below html, you want to hide text on click of button.

So you need to select button with id “myButton” as $(“#myButton”) and div with id helloWorldDiv as $(“#helloWorldDiv”)

For example:

Live demo :
jQuery selector example

So here on button click , we have hidden helloWorldDiv text.

Example on various selectors :

Element selector:

If you just write element name with $(), it will select all those element of that type.
For example: if you use $(“div”) , it will select all the div element in DOM.
In this example, on click of button , we will change text of all div present in the DOM.

Live demo:
jQuery element selector example

#Id selector :

For selecting element with id, you need to use $(#id).

Example:
So you need to select button with id “myButton” as $(“#myButton”) and div with id helloWorldDiv as $(“#helloWorldDiv”)

Live demo :
jQuery id selector example

So here on button click , we have hidden helloWorldDiv text.

class selector:

You can get all elements which use some class of CSS.
You need to use $(.className) to select all elements which uses that class. Example:


Live Demo:
jQuery class selector example

For more jQuery selectors, please refer jQuery selector API

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *