2014-11-25 65 views
1

我在包含多个iframe的页面上。我想通过javascript访问一个来操纵它上面的一些DOM元素。通过其src属性获取框架

问题是,iframe中没有id或name属性,只是一个src:

<iframe src="http://mysite/mypage/etc/etc/etc">divs and such in here</iframe> 

在这种情况下,我不能使用document.getElementById('someframe').contentWindow.document.getElementById(...),因为我没有一个ID来抓住框架。在这种情况下是否可以使用XPath查询或类似的查询? (如果它帮助这里有只有一个iframe中有其源设置为mysite/mypage。)

回答

3

您可以使用:

document.querySelector('iframe[src="http://mysite/mypage/etc/etc/etc"]') 

现代浏览器这只工作。 https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector

对于较旧的浏览器支持,请按标记名称选择所有iframe。然后缓解所有收到的元素并检查他们的src属性。

一个简单的例子:(代码可以而且应该在自己实现更好的书面)

var iframes = document.getElementByTagName('iframe'); 
var matches = []; 
for (el in iframes) { 
    if (el.src === 'http://mysite/mypage/etc/etc/etc') { 
     matches.push(el); 
    } 
}