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

Time:10-14

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

CodePudding user response:

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>

CodePudding user response:

CreateElement

Let's make this simple. In DOM all the elements are treated as objects. The document is also an object with attributes like body and methods like clear, location, and so on. So when you are creating an element with

let x=document.createElement('div')
console.log(typeof(x))
//returns object

The CreateElement returns an object and it does not create an attribute or anything for it. So the element is not connected to the document object.

Methods

x.click()

X is an object of HTMLElement and has methods like click and attributes like id and so on. But when you are doing like this

document.body.x.click()

The document has an attribute named body but the body object has no attributes like x

document.body.x //returns undefined

So finally the createElement method returns an object but it doesn't add the element as its attribute so when you are calling like this you get an undefined error.

  • Related