Check if an input field has focus in vanilla JavaS

2019-04-05 04:15发布

问题:

Using jQuery, I can test if an input field has focus like so:

if ($("...").is(":focus")) {
    ...
}

How do I do that without using jQuery?

回答1:

This question was answered here: Javascript detect if input is focused

Taken from the above answer:

this === document.activeElement // where 'this' is a dom object