Categories
JavaScript Answers

How to get the body’s content of an iframe in JavaScript?

Spread the love

Sometimes, we want to get the body’s content of an iframe in JavaScript.

In this article, we’ll look at how to get the body’s content of an iframe in JavaScript.

How to get the body’s content of an iframe in JavaScript?

To get the body’s content of an iframe in JavaScript, we can use the iframe’s contentDocument property.

For instance, we write

const iframe = document.querySelector("#id_description_iframe");
const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
const iframeContent = iframeDocument.querySelectorAll("#frameBody");

to select the iframe with querySelector.

Then we get the DOM object of the iframe’s content with

const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

And then we use querySelectorAll on the iframeDocument to select the elements we want from the iframe’s contents.

Conclusion

To get the body’s content of an iframe in JavaScript, we can use the iframe’s contentDocument property.

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 *