如何在添加纯 JavaScript 后获取 html 元素?

How to get html element after append with pure JavaScript?

我找到了一些JQuery解决方案,但我受学校任务限制无法使用纯Javascript,我需要使用尚未在[=22=中的特定早期附加元素] 替换为我的 CKEDITOR。

代码:

function newOption(){

     ...

     mainUL = document.getElementById("myUL");

     var inputA = document.createElement("input");
     inputA.type ="text";
     inputA.style = "margin-right: 45px";
     inputA.name = "option[]";
     inputA.id = inputID;

     mainUL.appendChild(inputA );

     CKEDITOR.replace(inputID).setData('Type anything you want ...');

     ...

}

通过用 CKEDITOR 替换我的输入,JS 会失败,因为输入通常仍然不在 DOM 中。我尝试使用

mainUL.innerHTML += "all elements like html text";

这是可行的,会立即将元素插入 DOM,但我不能使用 innerHTML,因为它会删除旧的侦听器(例如,JS 会将已选中的复选框从已选中设置为未选中,我的主要问题是什么,因为我必须尝试使用​​ append DOM 函数)。

尝试更改代码以将对 CKEDITOR.replace 的调用包装在 setTimeout:

setTimeout(function() {
  CKEDITOR.replace(inputID).setData('Type anything you want ...');
},0).

这将使浏览器有时间在尝试替换元素之前插入该元素。

我假设 inputID 中有一个有效值...