---
title: "Get iframe contents using queryselectors"
description: "Selecting data from iframes using the power of querySelectors. Practical notes and code examples on Get iframe contents."
url: "https://h3manth.com/scribe/get-iframe-contents-using-queryselectors/"
canonical_url: "https://h3manth.com/scribe/get-iframe-contents-using-queryselectors/"
markdown_url: "https://h3manth.com/scribe/blog/get-iframe-contents-using-queryselectors.md"
publishDate: "2012-06-08T00:00:00.000Z"
author: "Hemanth HM"
category: "javascript"
tags: ["javascript"]
word_count: 242
reading_time_minutes: 2
x_markdown_tokens: 600
content_signal: "ai-train=yes, search=yes, ai-input=yes"
---

# Get iframe contents using queryselectors

> Selecting data from iframes using the power of querySelectors. Practical notes and code examples on Get iframe contents.

With few security issues and hassles **iframes** have still managed to survive, the main reasons being:

* iframes help to beat the same origin policy and implement the cross domain origin policy.
* iframes allow multiple types of resources not just certain mime-types.

Maybe `sandbox`, `srcdoc` and `seamless` will help many, also the postMessage API!

But this article is not about explaining the good, bad and ugly of iframe, but it's about selecting data from iframes!

Using `document.frames['frame']` or `window.frames['frame']` to get the frame, and then using the `.innerHTML` is absolutely **wrong!**

Rather something like `document.getElementById('frame').contentWindow.document.body.innerHTML` is perfectly fine!

**But the fun is with doing the same with queryselectors!**

I'm a big fan of queryselectors and have been pawing at it doing things like:

* [JavaScript one liner extracting unique words from webpages](http://h3manth.com/content/javascript-one-liner-extracting-unique-words-webpages)
* [Native JS like jQuery](http://h3manth.com/content/native-js-jquery)
* [URL scrapping with javascript](http://h3manth.com/content/url-scraping-javascript)

And this time I got some time to play with iframes, so using queryselectors this is how one can get the contents of an iframe:

**Say you need the attributes of all the iframes that are present in the current page!**

```javascript
[].forEach.call(document.querySelectorAll('iframe'), function fn(elem) { 
    console.log(elem.attributes);
});
```

**Getting the HTML data from an iframe on the same lines...**

```javascript
[].forEach.call(document.querySelectorAll('iframe'), function fn(elem) { 
    console.log(elem.contentWindow.document.body.innerHTML);
});
```

**Querying specific content in an iframe:**

```javascript
[].forEach.call(document.querySelectorAll('iframe'), function fn(elem) { 
    console.log(elem.contentWindow.document.body.querySelectorAll('a'));
});
```

Hope you shall explore more on this, enjoy the raw power of JavaScript and happy hacking! :)
