[英]Javascript can't see html elements fetched form a local file
我有一个通过将 Word 文件转换为 html 创建的 html 文件。 我将 Word 生成的 html 代码复制粘贴到我添加到项目中的 html 文件中(我们称之为“local.html”)。
通过使用 fetch() function,我从 local.html 文件中检索了文本,并将数据(格式化为文本)添加到我的 index.ZFC35FDC70D5FC69D2698Z83A82 中 div 的 innerHTML
执行此操作的 js 代码是:
fetch("./local.html")
.then(response => {
return response.text();
})
.then(data => {
document.getElementById("aDivInIndexhtml").innerHTML = data;
});
Word生成的html标签被浏览器识别并正确呈现(我使用的是Opera)。
但是,javascript 没有看到这些元素(我对它们无能为力)。
我认为这是因为我将它们添加到 innerHTML 而不是将元素附加到 DOM。
因此,我尝试将包含这些元素的 div(“aDivInIndexhtml”)append 到我的 index.html 中的另一个 div。 同样的问题。 代码是:
var newDiv = document.createElement("div");
newDiv.appendChild("aDivInIndexhtml");
最奇怪的是当我这样做时:
console.log(document.getElementById("aDivInIndexhtml").children;
我得到一个列出这些元素的 HTMLCollection。
但是,如果我尝试使用例如访问集合中的任何元素:
document.getElementById("aDivInIndexhtml").children[0];`
或者
document.getElementById("aDivInIndexhtml").children.item(0);
我收到一条错误消息,提示它未定义。
如果我做:
document.getElementById("aDivInIndexhtml").children.length
我得到一个长度为 0 的集合,尽管在 console.loged 时同一个集合显示了许多元素!
所有元素都出现在浏览器的 DOM 中并被渲染,但对于 javascript 或 jquery,它们几乎不存在。
我认为这将是我的代码在 js 文件中的位置。 我把它移到了最后。 同样的问题。
它是否链接到 Word 生成的 html/xml 结构? 如果是这样,如何解决?
打印时
document.getElementById("aDivInIndexhtml").children[0];
和这个
document.getElementById("aDivInIndexhtml").children.item(0);
你得到未定义只是因为你的 div 元素 aDivInIndexhtml 还没有任何子元素并且它是一个数组,所以这就是它返回长度 0 的原因,因为它是空的。 所以要完成它,只需像这样在 aDivInIndexhtml div 中的 append 孩子:
改变这个
var newDiv = document.createElement("div");
newDiv.appendChild("aDivInIndexhtml");
至此
var newDiv = document.createElement("div");
var aDivInIndexhtml = document.getElementById("aDivInIndexhtml");
newDiv.appendChild(aDivInIndexhtml);
这里还有一件事是错误的,你在 appendChild 方法中传递了字符串“aDivInIndexhtml”,这是元素不在 DOM 中呈现的另一个原因,因为 appendChild 方法需要元素而不是字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.