The Wayback Machine - https://web.archive.org/web/20240910133732/https://www.geeksforgeeks.org/jquery-selectors-and-event-methods/
Open In App

jQuery | Selectors and Event Methods

Last Updated : 27 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

jQuery selectors allow targeting HTML elements using CSS-like syntax, enabling manipulation or interaction. Event methods facilitate handling user actions, like clicks or input changes, by attaching functions to selected elements, enhancing interactivity and dynamic behavior in web development.

jQuery selectors:

jQuery selectors are methods that allow you to target HTML elements using CSS-like syntax. They enable you to efficiently select and manipulate elements on a web page, simplifying DOM traversal and manipulation tasks.

Syntax:

 $("selector-name")

Elements Selector :

The Elements Selector in jQuery allows targeting HTML elements based on their tag names. It selects all elements of a specified type on a web page, enabling bulk manipulation or interaction with elements sharing the same tag.

Example : In this example, when the user clicks on button, the <h1> element gets hidden. Code :- html

<!DOCTYPE html>
<html>

<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
</head>

<body>
    <h1>Welcome to Geeks for Geeks !</h1>
    <h2>This is Web Technology section </h2>
    <br />
    <button>Hide</button>
    <script type="text/javascript">
        $("button").click(function () {
            $("h1").hide();
        });
    </script>
</body>

</html>
Output:

Jquery-element-selector

Id Selector :

The jQuery ID Selector targets an element on a web page by its unique identifier (ID). It uses the `#` symbol followed by the ID value to select and manipulate the specific element, offering efficient and precise DOM manipulation.

Example : In this example, when the user double clicks on button, the element with id = “gfg” gets hidden. Code:- html

<!DOCTYPE html>
<html>

<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
</head>

<body>
    <p id="gfg">Welcome to Geeks for Geeks !</p>
    <p id="GFG">Computer Science Portal </p>
    <br />
    <button>Hide</button>
    <script type="text/javascript">
        $("button").dblclick(function () {
            $("#gfg").hide();
        });
    </script>
</body>

</html>
Output:

Jquery-id-selector

Class Selector :

The jQuery Class Selector selects elements based on their class attribute. It uses the `.` symbol followed by the class name to target and manipulate multiple elements sharing the same class.

Example : In this example, when the user clicks on button, the element with class = “GFG” gets hidden. Code :- html

<!DOCTYPE html>
<html>

<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
</head>

<body>
    <p class="gfg">Welcome to Geeks for Geeks !</p>
    <p class="GFG">Explore More about GfG </p>
    <br />
    <button>Hide</button>
    <script type="text/javascript">
        $("button").click(function () {
            $(".GFG").hide();
        });
    </script>
</body>

</html>
Output:

Jquery-class-selector

jQuery Event methods:

jQuery event methods allow binding functions to HTML elements to respond to user interactions like clicks, hovers, or form submissions. They streamline event handling, providing cross-browser compatibility and simplifying the implementation of interactive web functionality.

Some of the events methods are given below

Method NameDescription
click()The click() method contains an function for event handling which gets invoked when the user clicks on the particular HTML element.
dblclick()The dblclick() method contains an function for event handling which gets invoked when the user double clicks on the particular HTML element.
mouseenter()The mouseenter() method contains an function for event handling which gets invoked when mouse pointer enters the particular HTML element.
mouseleave()The mouseleave() method contains an function for event handling which gets invoked when mouse pointer is removed from the particular HTML element which was selected earlier.
mousedown()The mousedown() method contains an function for event handling which gets invoked when mouse left, right or middle button is pressed while the mouse pointer is over the HTML element.
mouseup()The mouseup() method contains an function for event handling which gets invoked when mouse left, right or middle button is released while the mouse pointer is over the HTML element.
hover()The hover() method contains an function for event handling which gets invoked when mouse pointer enter and leaves the HTML element. It is a combination of mouseenter() and mouseleave() methods.

Get and Set Methods:

jQuery has various methods to get the value of an attribute and set the attribute to specific value.There methods are powerful enough to the change the website content and its style. Some of them are:

MethodDescription
text()Get or set the text content of selected HTML element.
html()Get or set the content of selected elements, including HTML.
val()Get or set the value of various form fields on the webpage.
attr()Get or set the value of various attributes on the webpage.
css()Get or set the value of various CSS properties on the webpage.

Example : In this example HTML document with jQuery library included. Buttons trigger jQuery events to change text, HTML content, input value, alignment, and CSS property of elements dynamically.

html

<!DOCTYPE html>
<html>

<head>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
    <style type="text/css">
        #e5 {
            width: 100px;
            height: 100px;
            border-radius: 0px;
            background-color: aqua;
        }
    </style>
</head>

<body>
    <p id="e1">Welcome.</p>
    <p id="e2">Learn and Explore</p>
    <p>
        <input type="text" id="e3" value="jQuery is powerful!" />
    </p>
    <p id="e4" align="left">Geeks for Geeks</p>
    <p>
    <div id="e5"></div>
    </p>
    <button id="gfg1">Change Text</button>
    <button id="gfg2">Change HTML</button>
    <button id="gfg3">Change Value</button>
    <button id="gfg4">Change Alignment</button>
    <button id="gfg5">Change Shape</button>
    <script type="text/javascript">
        $("#gfg1").click(function () {
            $("#e1").text("Geeks for Geeks");
        });
        $("#gfg2").click(function () {
            $("#e2").html("<b>Enrich your Knowledge.</b>");
        });
        $("#gfg3").click(function () {
            $("#e3").val("jQuery at Geeks for Geeks");
        });
        $("#gfg4").click(function () {
            $("#e4").attr("align", "center");
        });
        $("#gfg5").click(function () {
            $("#e5").css("border-radius", "50px");
        });
    </script>
</body>

</html>

Output:

Jquery-event-methods

jQuery Event Methods



Similar Reads

Define Selectors in jQuery and What are the types of selectors?
Selectors in jQuery: Selectors in jQuery are functions that primarily focus on selecting particular HTML elements and modifying them as per the action they need to perform. These selectors select particular HTML elements as per their name, element type, class, id, attributes or values of attributes, and much more. In other words, we can say that se
4 min read
Difference between the “nth-child()” and “nth-of-type()” selectors in jQuery
In this article, we will discuss all the differences between nth-child() and nth-of-type() selectors in jQuery. nth-child() Selector: This selector is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child, regardless of the type, of its parent. Syntax: :nth-child(number) { // CSS P
2 min read
JQuery Multiple ID selectors
Given an HTML document and the task is to select the elements with different ID's at the same time using JQuery. Approach: Select the ID's of different element and then use each() method to apply the CSS property on all selected ID's element.Then use css() method to set the background color to pink to all selected elements.Display the text which in
2 min read
Selectors in jQuery
The selector in jQuery is a function that selects nodes i.e. elements from the Document Object Model. In simple words, the selector is a function that is used to select/manipulate one or more HTML elements using jQuery. It plays a significant role in jQuery. With the help of a selector, we can select a particular HTML element and can perform variou
5 min read
How to use JavaScript variables in jQuery selectors ?
In this article, we will discuss how to use JavaScript variables in jQuery selectors. In the following examples, it can be seen that we have used the values stored in JavaScript Variables used inside the jQuery Selectors. Example 1: The concatenation technique can be applied in order to use the values stored in JavaScript variables. In the followin
2 min read
jQuery Selectors Complete Reference
jQuery selectors are used to select the HTML element(s) and allow you to manipulate the HTML element(s) in the way we want. It selects the HTML elements on a variable parameter such as their name, classes, id, types, attributes, attribute values, etc. Syntax: $("") Example: In this example, we will select a class by using jQuery .class Selector. C/
5 min read
What are the fastest/slowest selectors in jQuery ?
jQuery Selectors are used for selecting and manipulating HTML elements. In jQuery, there are mainly three selectors. ID selectorClass selectorElement selector Before moving forward, first, let's briefly see how these selectors are used. Element Selector: jQuery element selector selects the element on the basis of their name. Syntax: $(''element") E
4 min read
How jQuery Selectors are Executed ?
jQuery is a fast, lightweight JavaScript library designed to simplify HTML DOM tree traversal, manipulation, event handling, CSS animation, and Ajax. The main objective of jQuery is to provide an easy way to use JavaScript on your website to make it more interactive and attractive. It is widely famous for its philosophy of “Write less, do more.” be
2 min read
How to use OR Operation in jQuery Attribute Selectors ?
In this article, we will see how to use OR operation in jQuery Attribute Selectors. To use the OR operation in the attribute selector, we will use the comma operator (,) on attributes or attribute values. Syntax: $(".class1, .class2, ...") { // Code } Approach: First we will create some HTML div elements with their class names and then use the comm
2 min read
JQuery Selectors
What is a jQuery Selector?jQuery selectors are functions that allow you to target and select HTML elements in the DOM based on element names, IDs, classes, attributes, and more, facilitating manipulation and interaction. Syntax: $(" ")Note: jQuery selector starts with the dollar sign $, and you enclose the selector inside parentheses (). We will ex
5 min read
jQuery Event Methods Complete Reference
An event refers to the actions performed by the site visitor during their interactivity with the website (or webpage). There can be various types of events such as The user clicks on the button.The user moves the mouse pointer over an image.The user pressed any key from the keyboard, etc. Syntax: $(selector).method(function) Example: C/C++ Code
6 min read
Wildcard Selectors (*, ^ and $) in CSS for classes
Wildcard selectors can be used with attribute selectors. The asterisk (*) matches any character, the caret (^) matches the start, and the dollar sign ($) matches the end of an attribute value. For example, .class* selects all elements with a class attribute containing "class" anywhere, .class^ selects those starting with "class," and .class$ select
3 min read
Difference Between Descendant and Child Selectors in CSS
The Descendant selector and child selector in CSS are both used to target specific elements within the document structure, but they differ in their level of specificity and targeting. Descendant SelectorIt uses a space to select all descendants of a particular ancestor. In the below example, It selects all matching elements, regardless of their dep
1 min read
CSS Selectors Complete Reference
CSS selectors are used to select HTML elements based on their element name, id, class, attribute, and many more. Example: Below the HTML/CSS code shows the functionality of ::after selector. C/C++ Code &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; p::after { content: &quot; - Remember this&quot;; background-color: blue; } &lt;/style
4 min read
Advanced Selectors in CSS
Selectors are used for selecting the HTML elements in the attributes. Some different types of selectors are given below: Adjacent Sibling Selector: It selects all the elements that are adjacent siblings of specified elements. It selects the second element if it immediately follows the first element. Syntax: It selects ul tags that immediately follo
5 min read
Less.js Parent Selectors
The Parent Selectors in LESS.js are used to select elements with the specific parents when modifying an existing class or pseudo-class to an existing selector. It is denoted by the ‘&amp;’ (ampersand) operator. It is important in the pre-processor to have a clean code with the hierarchy of like DOM tree in CSS. Different types of Parent Selectors:
3 min read
Which characters are valid in CSS class names/selectors?
It is very easy to choose a valid class name or selectors in CSS just follow the rule. A valid name should start with an underscore (_), a hyphen (-) or a letter (a-z)/(A-Z) which is followed by any numbers, hyphens, underscores, letters.It cannot start with a digit, starting with the digit is acceptable by HTML5 but not acceptable by CSS.Two hyphe
2 min read
SASS | Placeholder Selectors
Placeholder is another special kind of selector. It is used when you are writing your own SASS library. Its work is very similar to mixin without arguments. Placeholder selector starts with a % sign. Syntax: %( name_of_selector ) { property: value; ... } Placeholder selectors are excluded in the compilation of the SASS file ( This defines the main
2 min read
Why are dashes preferred for CSS selectors / HTML attributes ?
CSS is a hyphen-delimited syntax language which means while writing HTML attributes we can use hyphen(-). Example: font-size, line-height, background-color, etc... There are various reasons to preferring hyphen(-): In CSS, one can use underscore(_) instead of hyphen(-) for CSS selectors(class, id, span, ...), but preference is given based on its ea
2 min read
How to place background image using ::before pseudo selectors in CSS ?
Given a web page and the task is to place the background image on web page using ::before pseudo selector. The ::before pseudo selector is used to place something before the content of the selected items. Syntax: .container::before{ content: ''; background: url(image file); position:absolute; top:0px; left:0px; } Approach: The ::before pseudo selec
2 min read
How to combine parent using ampersand (&amp;) with type selectors in SASS ?
Ampersand or "&amp;" is a powerful feature of SASS. It enhances the readability of code by using nesting statements, which takes an edge over conventional CSS. We can nest the css class any number of times but most of the times it's not required. Syntax: parent { some_styling; &amp; .child_element { some_stylings; } /* :hover, :active, :visited etc
2 min read
Why do browsers match CSS selectors from right to left ?
Cascading Style Sheets fondly referred to as CSS, is a simply designed language intended to simplify the process of making web pages presentable. CSS allows you to apply styles to web pages. More importantly, CSS enables you to do this independently of the HTML that makes up each web page. It describes how a webpage should look: it prescribes color
3 min read
Less.js Extending Nested Selectors
LESS is a simple CSS pre-processor that makes it possible to create manageable, customizable, and reusable style sheets for websites. LESS is a dynamic style sheet language that increases the working power of CSS. LESS is cross-browser compatible. CSS pre-processor is a scripting language that improves CSS and gets compiled into regular CSS syntax
2 min read
How CSS Styles Conflicts Between Selectors ?
CSS conflicts between selectors occur when two or more selectors have conflicting styles applied to the same element, leading to unexpected results. In such cases, the browser has to decide which style to apply to the element. In this article, we'll understand what causes conflicting styles in CSS, and how to avoid and resolve them. Causes of Confl
4 min read
Explain Selectors in React Redux
Selectors in React Redux serve as efficient filters for accessing specific data from the Redux store. They encapsulate logic for data retrieval, optimizing performance, and promoting code reusability. By using memoization, selectors cache results to prevent unnecessary re-renders, thus enhancing overall application efficiency. They make efficient i
2 min read
10 CSS Selectors Every Developer Should Know
What's the first thing for any website to create a good impression on a user? ...  Yes...it's the user interface for any website. Every developer knows how important it is to create a beautiful design for users to interact with any website. Giving styling to web pages smartly in a minimal amount of time is not an easy task if you don't have a good
9 min read
Why are selectors considered best practice in React Redux ?
Redux selectors are functions that allow for efficient and structured extraction of specific data from the Redux store. They can calculate derived data, which helps Redux maintain the minimum possible state. Selectors are also efficient, as they are only recomputed if any of their arguments change. Why are selectors considered a best practice in Re
3 min read
Different ways to retrieve specific pieces of state using selectors
In Redux applications, selectors are functions that facilitate the retrieval of specific pieces of state from the Redux store. Selectors play a crucial role in decoupling components from the store's structure and improving performance by memoizing computed values. Let's explore two approaches to retrieving specific states using selectors. Prerequis
4 min read
How to retrieve specific pieces of state using selectors
In Redux, there are some techniques used to retrieve specific pieces of state from the Redux store. In this article, we will create a to-do list application using Redux and React, and we use the Reselect library for optimized state selection. This app provides basic functionalities such as adding new to-dos and displaying a list of existing to-dos.
3 min read
CSS Child vs Descendant selectors
Understanding the differences between child and descendant selectors in CSS is crucial for precise styling. These selectors allow you to target HTML elements based on their hierarchical relationships, ensuring you apply styles accurately. Child Selector:The child selector (element &gt; element) matches all elements that are direct children of a spe
2 min read