【问题标题】:Don't know how to access a #document in the DOM [duplicate]不知道如何访问 DOM 中的#document [重复]
【发布时间】:2018-11-26 17:59:28
【问题描述】:

我正在尝试使用 Javascript 访问 DOM 中的 #document,但我不知道如何访问,它在下图中。

#document example

就像 Body>div 类>div.horizo​​ntal container>div.main center>div#ph-main-centre.placeholder>div-optiframeappincludecomponent>iframe#virtualsAppMain.iframecontainer>html>body.ng-scope.html是我想要访问的。 var ifframe = document.getElementbyid(iframe); iframe.contentDocument //返回空值// iframe.contentWindow //返回受限// 如何访问 iframe 的内容?

【问题讨论】:

标签: javascript dom


【解决方案1】:

如果您找到包含#document 的框架,您可以以frame.contentDocument 访问内容。

【讨论】:

  • iframe.contentDocument 返回 null。
  • 只有在跨域头设置正确且同域的情况下才能访问contentDocument。
  • contentDocument 返回 null 但 contentWindow 返回受限。
  • var xhr = new XMLHttpRequest(); xhr.responseType = "document"; xhr.withCredentials = "true"; xhr.method = "GET"; xhr.origin = "example.com"; xhronreadystatechange = function() {if(xhr.readyState === 4 && xhr.status === 200)console.log(xhr.responseText)}; xhr.open('GET','example.com','True'); xhr.setRequestHeader('Access-Control-Allow-Origin','example.com'); xhr.send();
  • 我迷路了。@Strikeskids。
【解决方案2】:

访问后您想达到什么目的?能否提供示例代码?

要在 JS 中按类访问 DOM 元素,像这样使用它。

var coolElement = document.getElementsByClassName("coolelementclassname")

另请参阅 MDN。 HERE

【讨论】:

  • 我想访问它的子元素到另一个元素。 `var ifframe = document.getElementById('iframe'); ifframe.contentwindow/contentdocument; var iframedoc = ifframe.contentWindow/document; ifframedoc.body; ifframedoc.body.childelement[1];直到我正在寻找的元素。 @马里奥
猜你喜欢
  • 1970-01-01
  • 2017-05-29
  • 2017-09-22
  • 2022-01-26
  • 1970-01-01
  • 2021-07-18
  • 2012-09-02
  • 2014-04-15
  • 2023-03-30
相关资源
最近更新 更多