Focus a Particular Element with Div Class in JavaScript



In this article, we will learn to focus on a particular element with a div class in JavaScript. In JavaScript setting focus on an element is commonly done using the focus() method.

What is the focus() method?

The focus() method in JavaScript is used to bring a specific element into focus. This means the element becomes active, allowing the user to interact with it, such as typing in an input field or highlighting a section of the webpage.

Syntax

element.focus();

Here, the element is the DOM element that will receive the focus.

Using JavaScript to Focus on a Class Element

If an element has a class rather than an id, we can select it using document.querySelector() or document.querySelectorAll(). The first matched element can then be focused using the focus() method.

Following are the steps to focus on a class element using HTML and JavaScript ?

  • The <span> element has the class TEXT_FOCUS and a tabindex="-1" attribute, making it focusable.
  • A button with id="focusButton" is used to trigger focus on the TEXT_FOCUS element.
  • When the button is clicked, document.querySelectorAll('.TEXT_FOCUS')[0].focus(); is executed to focus on the first element with the TEXT_FOCUS class.

The following is the JavaScript for the focus on a class element ?

<script>
   document.getElementById('focusButton').addEventListener('click', function() {
      document.querySelectorAll('.TEXT_FOCUS')[0].focus();
   });
</script>

Example

Below is an example to focus on a particular element with a div class in JavaScript ?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<span class="TEXT_FOCUS" tabindex="-1"><center>TEXT BOX FOR
FOCUS</center></span><br>
<button id="focusButton">click me to get the tab on focus</button>
<script>
   document.getElementById('focusButton').addEventListener('click', function() {
      document.querySelectorAll('.TEXT_FOCUS')[0].focus();
   });
</script>
</body>
</html>

Output

When you click the button, the focus will be on a particular element. The snapshot is as follows ?

Conclusion

The focus() method in JavaScript is a powerful tool that allows developers to bring a specific element into focus dynamically. By using document.querySelector() or document.querySelectorAll(), we can select and focus on elements with a specific class instead of relying on id attributes.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-04T19:49:21+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started