Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
Why I can not access an Element (which has been created by JS) using document.body.myElement?
let myElement = document.createElement("div")

I can access the element by:

myElement.anyMethod

But I can not access by:

document.body.myElement.anyMethod

So why can we access body by:

document.body.anyMethod

But we can not access the element by:

document.body.myElement.anyMethod
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!