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

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.