'JS: select class inside of <iframe> [duplicate]

I have an <iframe> on my page.

Inside of the page, that is loaded in the iframe, is this: <span class="test">TEST</span>

I would like to change the color of TEST to red.


This is what I wrote:

var test = document.querySelector("iframe").contentWindow.document.querySelector(".test");

test.style.color = "red";

Seems logical, but it doesn't work. – What's going on?

This is the error message that I'm getting: Error



Solution 1:[1]

I have tried this and it seems to work for me. Perhaps its some other issue?

Things to keep in mind:

  1. You cant modify a page from a domain that isnt your own (so if the code is running on localhost, you can only modify other loaded files on localhost) This is a CORS issue

  2. You need to wait for the IFrame to load the document before modifying it.

Other than that I took a look at your code, and the code on the link below and I tested using querySelector in an iframe and it seemed to work.

Take a look at this if you need more help: https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentWindow

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Roko C. Buljan