Get iframe of given ID

2019-08-30 19:32发布

问题:

How do you select the iframe DOM Object on the page if you know the iframe's ID? Assume there might be multiple iframes on the page and you don't know the position of the one in question, and also no jQuery solutions please. I came up with the following, however, I expect it can be much more trivial.

EDIT. I am trying to get the DOM object, so that I can access properties such as window.frames[0].innerHeight

function getIframe(id) {
    var iframe=null;
    for (var i = window.frames.length - 1; i >= 0; i--) {
        if(window.frames[i].frameElement.id==id){iframe=window.frames[i];break;}
    }
    return iframe;
}

回答1:

See this answer:

Access iframe elements in JavaScript

window.frames['myIFrame']

EDIT:

I made some tests on FF and Chrome and came up with the following conclusions.

window.frames["myFrame"] returns:

    `[object HTMLIFrameElement]` when on FF (v24)
    `[object Window]` when on Chrome (v 30.0.1599.101)

we can make a control like this for HTMLIFrameElement property contentWindow to get the iframe Window:

var myFrame = (window.frames["myFrame"].contentWindow ? window.frames["myFrame"].contentWindow : window.frames["myFrame"])

This way in the variable myFrame is stored the Window object.

If now we want to get the DOM element HTMLIFrameElement we can simply do:

var domElement = myFrame.frameElement

Hope this will be useful.



回答2:

var el = document.querySelector('#test');

var matches = el.querySelectorAll('iframe');

readmore:http://slides.html5rocks.com/#new-selectors