简体   繁体   中英

How to remove class from div inside iframe contents

I have this structure, and i want to remove test2 class from div

iframe1 -> iframe2 -> <div class="test1 test2">.... </div>

I am able to access iframe2 but I am not able to find above div in second iframe.

here what I have tried

document.querySelectorAll('iframe').forEach(item => {
            var y = item.contentDocument.body.getElementsByTagName("iframe");
            setTimeout(() => {
                y[0].style.width = '100vw'; 
                $(y[0]).contents().find(".test2").removeClass('.test2')
            }, [500])
        })

y[0].style.width = '100vw';

this is working. but I am not able to find div with test2 class

console.log(y[0]) is iframe as expected.

在此处输入图像描述

y[0].contentDocument is null

if anyone can help me with this. Thanks in advance

Also in some answers I found that we can't change contents of iframe if it is of cross origin. but here I have same origin.

I just want some css changes either i need to remove test2 class or override it.

Assuming a mock structure like the following, all with the same Origin:

index.html

<body>
  <iframe id="iframe1" src="index2.html"></iframe>
</body>

index2.html

<body>
  <iframe id="iframe2" src="index3.html"></iframe>
</body>

index3.html

<body>
  <div class="test2">Foo</div>
</body>

You would need the following confusing code.

var f1 = $("#iframe1");
var f2 = $("#iframe2", f1.contents());
var target = $(".test2", f2.contents());
target.removeClass("test2");

This is based on the following: Selecting an element in iframe with jQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM