Javascript无法看到从本地文件中获取的html元素

问题描述 投票:0回答:1

我有一个通过将Word文件转换为html创建的html文件。我将Word生成的html代码复制粘贴到我添加到项目中的html文件中(我们称其为“ local.html”)。

[通过使用fetch()函数,我从local.html文件中检索了文本,并将数据(格式为文本)添加到了index.html文件中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”)附加到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结构?如果是这样,如何解决?

javascript html dom ms-word fetch
1个回答
0
投票

同时打印此

document.getElementById("aDivInIndexhtml").children[0];

和此

 document.getElementById("aDivInIndexhtml").children.item(0);

您正因为div元素aDivInIndexhtml还没有任何孩子而变得不确定,并且它是一个数组,所以这就是为什么它返回长度0的原因,因为它为空。因此,只需将子代添加到aDivInIndexhtml div中即可:

更改此

   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方法要求元素不是字符串。

© www.soinside.com 2019 - 2024. All rights reserved.