你必须等待内容加载,然后访问内容,我已经对你的fiddle做了一个小更新,由于跨来源,它在那里无法工作。
<body>
<div class="div1">
stuff
</div>
<div class="div2">
<a href="https://jsfiddle.net/user/login/">link</a>
</div>
</body>
function embed(src, target){
return new Promise(function(resolve, reject){
let iframe = document.createElement("iframe");
iframe.src = src;
iframe.style = "width: -webkit-fill-available;height: -webkit-fill-available;";
iframe.onload = function(){
resolve(iframe.contentWindow.document);
};
target.parentNode.replaceChild(iframe, target);
});
}
let href = document.querySelector('.div2 a').getAttribute("href"),
target = document.querySelector('.div1');
embed(href, target).then(function(doc){
console.log( doc.querySelector('h2') );
});
https://jsfiddle.net/zhhL9rjr/6/
但如果从同一个域加载某些内容,则应该可以正常工作。