首页 > 解决方案 > 获取多个 html 文档中的元素

问题描述

我的系统中有一个功能,可以使用外部库将语音转录为文本。
这就是库呈现的内容:
我需要的非常简单:从生成的 textareas 中获取文本。
textareas 是在没有任何名称或 ID 的情况下呈现的,因此我只能在 Google Chrome 控制台中按类访问它们。每当我尝试在我的 javascript 代码中按类获取它们时,我都会得到一个 [0] 元素的数组。

我认为问题在于这个库呈现了一个新的#document,而我无法在我的$(document).ready函数中获取它的内容,因为它限定了“父”文档的范围。 它是如何呈现的。
对此有什么想法吗?谢谢你。

标签: javascripthtmljquerydom

解决方案


我希望下面的代码有所帮助。

// Get you iframe by Id or other way
let iframe = document.getElementById("myFrame");

// After iframe has been loaded
iframe.onload= function() {   
    // Get the element inside your iframe
    // There are a lot of ways to do it
    // It is good practice to store DOM objects in variables that start with $
    let $elementByTag = iframe.contentWindow.document.getElementsByTagName("p")[0];
    let $elementById = iframe.contentWindow.document.getElementById("elementId");
    let $elementByClass = iframe.contentWindow.document.getElementsByClassName("classHere");
    let $elementBySelector = iframe.contentWindow.document.querySelector("#dad .classname");
    
    // After get the element extract the text/html
    let text = $element.innerText
    let html = $element.innerHTML
};

推荐阅读