Categories
JavaScript Answers

How to set focus to iframe contents with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *