How to find a div inside of an iframe

前端 未结 3 574
囚心锁ツ
囚心锁ツ 2021-01-05 00:41

I am trying to use jquery to find a div inside an iframe. Is there a better way than the one I\'m using below?

$(\'#Iframe\').contents().find(\'#MyDiv\')

fu         


        
相关标签:
3条回答
  • 2021-01-05 01:25

    Use selector context:

    var frame = $('#frame_id');
    var div = $('#mydiv', frame);
    
    0 讨论(0)
  • 2021-01-05 01:30

    I don't think the jQuery can access the contentWindow/Document's content in that way. In the past, I've had to do this:

    $('#iframe').each(function() {
        $('#MyDiv', this.contentWindow.document||this.contentDocument);
    });
    

    ** Note that this.contentWindow||this.contentDocument is required to work correctly across IE and most other browsers. Once you get the content window, you need to select the document. Then you can use jQuery to manipulate or traverse the DOM, but only if the iframe's source is in the same domain.

    ** Updated to fix error where we don't specify the document after we get the contentWindow/Document.

    0 讨论(0)
  • 2021-01-05 01:30

    This will only work if the Iframe source is in the same domain as your page, if not the browser wont allow it for security reasons

    0 讨论(0)
提交回复
热议问题