PHP前端开发

js如何获取iframe里面的元素

百变鹏仔 3天前 #JavaScript
文章标签 元素
要获取 iframe 中的元素,可以:直接访问 iframe 元素,通过 contentdocument 或 contentwindow 获取内部元素。使用 getelementbyid 访问具有特定 id 的元素。使用 queryselector 选择具有特定 css 选择器的元素。使用 queryselectorall 选择所有具有特定 css 选择器的元素。但请注意跨域限制,不能访问不同域的 iframe 中的元素。

如何获取 iframe 中的元素

直接访问 iframe

最直接的方法是直接访问 iframe 元素并通过其 contentDocument 或 contentWindow 属性获取内部元素。

const iframe = document.querySelector('iframe');const iframeDocument = iframe.contentDocument;const iframeWindow = iframe.contentWindow;const element = iframeDocument.getElementById('elementId');

使用 getElementById

可以通过 getElementById 方法访问 iframe 中具有特定 ID 的元素。

const element = iframeDocument.getElementById('elementId');

使用 querySelector

querySelector 方法可用于选择 iframe 中具有特定 CSS 选择器的元素。

const element = iframeDocument.querySelector('selector');

使用 querySelectorAll

querySelectorAll 方法可用于选择 iframe 中所有具有特定 CSS 选择器的元素。

const elements = iframeDocument.querySelectorAll('selector');

注意: