Home »
jQuery »
jQuery Selectors
jQuery :focus Selector
jQuery | :focus Selector: Learn about the :focus Selector with its usages, syntax, examples.
Submitted by Pratishtha Saxena, on December 15, 2022
:focus Selector
In jQuery, selectors are a parameter through which we can select the HTML element. Selectors can comprise – class names, ids, tag names, attributes, etc. Basically, by using selectors, the appropriate HTML-DOM element can be selected and hence performed actions on it. Here, we are discussing the jQuery :focus Selector.
The jQuery :focus selector selects all the elements that have been focused.
The focus is a property that denotes the element that has either its property set as 'focused' or is currently been focused by the user.
The focus() method is an inbuilt jQuery method that helps to achieve the focus of the selected element. Generally, this is used with the input tag of the form element, but now it can be implemented by all the other elements too.
Hence, by using the :focus selector, we can get all the currently focused elements and perform actions only on those selected ones.
:focus Selector Syntax
$(':focus');
It is used along with the ':' symbol in front. This selector selects all the focused elements at once and hence allows you to perform the required actions on them altogether. The following example shows how the focused field is selected.
jQuery :focus Selector Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h2>jQuery - Focus Selector</h2>
<p>Select any input box to get the focus.</p>
<hr>
<br>
Name: <input type="text" id="one"><br><br>
Email: <input type="email" id="two"><br><br>
Contact: <input type="number" id="three"><br>
<h4>Thank You !</h4>
<hr>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('input#two').focus();
$(':focus').css('background-color','#FE8700');
});
</script>
</html>
Output: