如何在iframe的文档元素中检查正文是否为空?

时间:2018-10-16 06:45:59

标签: javascript

要检查Google广告生成的body区域中的iframe元素是否为空。这是我尝试过的结果重新调整了。效果不好。也许方法不正确。

<iframe id='abc' scrolling="no" marginwidth="0" marginheight="0" frameborder="0" data-load-complete="true">
    #document
        <html>
            <head></head>
            <body>
                <scirpt>...</script>
                <scirpt>...</script>
                <div>...</div>
            </body>
        </html>
</iframe>

var iframe = document.getElementById("abc");
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
alert(iframeDocument.getElementsByTagName("body"));
// It printed: [object HTMLCollection]
alert(iframeDocument.getElementsByTagName("body").item(0).innerHTML);
// It printed: "". But here it isn't empty.

2 个答案:

答案 0 :(得分:0)

alert(iframeDocument.getElementsByTagName("body").childNodes

答案 1 :(得分:0)

要检查html元素是否有子元素,可以使用HTML DOM children propertychildNodes属性:

这是W3Schools的一个一般示例:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get the tag names of the body element's children.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var c = document.body.children;
    var txt = "";
    var i;
    for (i = 0; i < c.length; i++) {
        txt = txt + c[i].tagName + "<br>";
    }

    document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>