close

How can I check if my Element ID has focus?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How can I check if my Element ID has focus? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How can I check if my Element ID has focus ?

  1. How can I check if my Element ID has focus ?

    can I check if my Element ID has focus Use document.activeElement
    Should work.
    P.S getElementById("myID") not getElementById("#myID")

  2. How can I check if my Element ID has focus ?

    can I check if my Element ID has focus Use document.activeElement
    Should work.
    P.S getElementById("myID") not getElementById("#myID")

Method 1

Compare document.activeElement with the element you want to check for focus. If they are the same, the element is focused; otherwise, it isn’t.

// dummy element
var dummyEl = document.getElementById('myID');

// check for focus
var isFocused = (document.activeElement === dummyEl);

hasFocus is part of the document; there’s no such method for DOM elements.

Also, document.getElementById doesn’t use a # at the beginning of myID. Change this:

var dummyEl = document.getElementById('#myID');

to this:

var dummyEl = document.getElementById('myID');

If you’d like to use a CSS query instead you can use querySelector (and querySelectorAll).

Method 2

Use document.activeElement

Should work.

P.S getElementById("myID") not getElementById("#myID")

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment