Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda