JS操作未跨域iframe里的DOM

这里简单说明两个方法,都是未跨域情况下在index.html内操作b.html内的 DOM。

如:index.html内引入iframe,在index内如何用JS操作iframe内的DOM元素?

先贴下index.html和iframe引入的a.html内容。

index->

<div class="d1">
        <iframe src="a.html" frameborder="0" name="one" id="iframeId"></iframe>
    </div>

a.html

<div id="dd">
        <h1>iframe里的元素!</h1>
    </div>

法一:

var d=window.frames["one"].window;
    d.onload=function(){
        console.log(d.document.getElementById("dd"));
    };

法二:

JS动态创建iframe并插入

var ifr = document.createElement('iframe');
    ifr.src = 'a.html';
    document.body.appendChild(ifr);
    ifr.onload = function(){
        var doc = ifr.contentDocument || ifr.contentWindow.document;
        // 在这里操纵b.html
        console.log(doc.getElementById("dd"));
    };

两种的输出结果都是

原文地址:https://www.cnblogs.com/-walker/p/5549259.html