Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda