How does JavaScript focus() method works?


Javascript focus() methods helps to highlight a HTML form element. It sets the element as an active element in the current document. In current documentation, focus can be applied to only one single element. The focus can be applied either to a text, a button, etc.  




In the following example, initially, the text "Tutorialspoint" is in an anchor tag 'a', which as an id called 'focus'. Later on, a function is declared in which the id is called using a DOM method and focus() method is applied on it to change the color of text "Tutorialspoint" to red. Here a button is used for the click event.

Live Demo

   a:focus, a:active {
      color: red;
<a href="" id="focus">Tutorialspoint</a>
<input type="button" value="getfocus" onclick="getfo()">
   function getfo() {

After executing the above code we will get the following image displayed on the screen.

Once we click on the get focus button we will get the following output.


Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started