How to set focus to iframe contents with JavaScript?

Sometimes, we want to set focus to iframe contents with JavaScript.

In this article, we’ll look at how to set focus to iframe contents with JavaScript.

How to set focus to iframe contents with JavaScript?

To set focus to iframe contents with JavaScript, we call the iframe’s body’s focus method.

For instance, we write

document
  .getElementsByName("iframe_name")[0]
  .contentWindow.document.body.focus();

to get the iframe with getElementsByName.

Then we get its body element with contentWindow.document.body.

And then we call focus to focus on it.

Conclusion

To set focus to iframe contents with JavaScript, we call the iframe’s body’s focus method.