Why I can not access to an Element (has been created by JS) using documnet.body.myElement

let myElement = document.createElement("div")

I can access by :

myElement.anyMethod

But I can not access by :

document.body.myElement.anyMethod

So why we can access to body by :

documnet.body.anyMethod

But we can not access to the element by :

document.body.myElement.anyMethod

Answer

You’re missing a step in your code if you’re expecting to reference it from the DOM (via document.body... or document.getElement...). You need to append the element to a particular place where you want it. This reference page shows a simple example, but I’ll share an example related to your code here:

let myElement = document.createElement("div");
myElement.innerHTML = "It works!";
// you can replace the following with `document.body.append(myElement)`
document.getElementById("body").append(myElement);
<div id="body"></div>