如何在iframe中获取div的对象

时间:2013-06-27 09:50:35

标签: javascript jquery dom iframe

我有2个html个文件和一个IFrame个文件。

结构是,

enter image description here

我可以获得outside.htmliframe的对象。但是我无法得到inside.html的对象。

我的inside.html将是,

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath() %>/css/chat.css">
<title>Heart JSP page</title>

</head>
<body>

    <div id="messageArea" class="divBorder">

     Chat Interaction id is : Some value.

    </div>
    <div id="enterMessage" class="divBorder">
    Your message Area
    </div>
</body>
</html>

我的javascript

if($("#chatMessageArea").length){

    alert("outside.html Object is present !");

    if($("#ch"+intxnId).length){

        alert("IFrame Object is present !");

        if($("#ch"+intxnId).contents().find("#messageArea").length){
            alert("inside.html Object is present !");
        }else{
            alert("inside.html Object is not available !");
        }

    }else{
        alert("IFrame Object is not available !");
    }
}
else{
    alert("outside.html Object is not available  !");
}

注意:

#chatMessageArea - outside.html的div的ID

#chintxid - iframe的ID

#messageArea - inside.html中div的ID

任何人都可以帮助获取inside.html的对象。

3 个答案:

答案 0 :(得分:0)

试试这个:

var ifr = document.getElementById('chintxid');
ifr.contentDocument.getElementById('messageArea').innerHTML = "reached!";

您需要先获取iFrame ID,然后在其中获取所需内容。让我知道你是否正在寻找..

答案 1 :(得分:0)

使用此辅助函数获取iframe文档

getFrameContentDocument = function(frame) {
   var doc = frame.contentDocument || frame.contentWindow.document;
   return doc;
};

然后代码将是

var iframe = document.getElementById("ch" + intxid);
var iframeDoc = getFrameContentDocument(iframe);
// You can now get elements in this iframe 
var messageArea = iframeDoc.getElementById("messageArea");

答案 2 :(得分:0)

得到解决方案,

if($("#chatMessageArea").length){

    alert("chatMessageArea Object is present !");

    if($("#ch"+intxnId).length){

        if($("#ch"+intxnId).contents().find('body').find("#messageArea").length){

            alert("messageArea Object is present !");
        }else{
            alert("messageArea Object is not available !");
        }
    }else{
        alert("IFrame Object is not available !");
    }
}
else{
    alert("chatMessageArea Object  not available  !");
}