Search code examples
javascripthtmldomckeditor

How to get html element after append with pure JavaScript?


I found some JQuery solutions, but I am limited by school task restrictions to use pure Javascript, and I need to use specific early appended element that is still not in DOM for replacing by my CKEDITOR.

Code:

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 ...');

     ...

}

By replacing my input with CKEDITOR will JS fail, because input, commonly, is still not in DOM. I tried to use

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

and this is working and will immediately insert elements into DOM, but I can't to use innerHTML, because it will remove old listeners (for example checked checkboxes that JS will set from checked to unchecked, what is my main problem due to I have to try using append DOM function).


Solution

  • Try changing the code to wrap the call to CKEDITOR.replace in a setTimeout:

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

    This will allow the browser time to insert the element before trying to replace it.

    And I assume that inputID has a valid value in it...