Open In App
Related Articles

HTML DOM focus() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

DOM focus() method is used to give focus to an element and also to remove the focus with the help of blur() method. We can apply focus to any element and enable it by doing some operation. For example, we can give focus to some text by clicking a button.

Syntax:

Object.focus()

Example-1: 

HTML




<!DOCTYPE html>
<html>
<head>
    <title>DOM focus() Method</title>
    <style>
        input[type=text]:focus {
            background-color: red;
        }
    </style>
</head>
  
<body>
    <center>
        <input type="text" id="gfg" value="GeeksForGeeks">
        <h2>DOM focus() Method </h2>
        <button type="button" onclick="geek()">
            Submit
        </button>
        <script>
            function geek() {
                document.getElementById("gfg").focus();
            
        </script>
    </center>
</body>
</html>


Output: 

Before applying focus:

  

After applying focus:

  

Example-2: 

HTML




<!DOCTYPE html>
<html>
<head>
    <title>DOM focus() Method</title>
    <style>
        a:focus {
            background-color: magenta;
        }
    </style>
</head>
<body>
    <center>
        <h1 style="color:green;">
            GeeksForGeeks
        </h1>
        <h2>DOM focus() Method</h2>
        <a href="www.geeksforgeeks.com" id="geek">geeksforgeeks</a>
        <br>
        <button type="button" onclick="geeks()">
            Submit
        </button>
        <script>
            function geeks() {
                document.getElementById("geek").focus();
            
        </script>
    </center>
</body>


Output: 

Before applying focus:

  

After applying focus:

  

Supported Browsers: The browser supported by DOM focus() method are listed below:

  • Google Chrome 1.0 and above
  • Edge 12.0 and above
  • Internet Explorer 5.5 and above
  • Firefox 1.5 and above
  • Opera 8 and above
  • Safari 3 and above

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 13 Jun, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials