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

147
Visualizações
can't select element with dom, after creating that element with other function - appendChild

How i'm supposed to select my element that have been created by function. First function is working well, but while i'm trying to select the element that been created in that function, it doesn't work

let d = document.querySelector(".lop");
let body = document.querySelector(".body");

d.addEventListener("click", function () {
  let c = document.createElement("p");
  c.appendChild(document.createTextNode("lopas"));
  body.appendChild(c);
});

document.querySelector("p").addEventListener("click", function () {
  console.log("Hi");
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="lop">s</div>
    <div class="body"></div>

    <script src="script.js"></script>
  </body>
</html>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Problem:

  • You create the p element at the moment when you click on .lop
  • You try to add the event listener at the page load. At this point there is no p tag at all.

Solution:

  • Add the event listener after you created the p tag.
  • You could also use the reference c instead of querySelector.

let d = document.querySelector(".lop");
let body = document.querySelector(".body");

d.addEventListener("click", function() {
  let c = document.createElement("p");
  c.appendChild(document.createTextNode("lopas"));
  body.appendChild(c);

  c.addEventListener("click", function() {
    console.log("Hi");
  });
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>

<body>
  <div class="lop">s</div>
  <div class="body"></div>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

That's because you are attempting to attach a click event to your paragraph tag before its ever been added to the DOM.

You will need to move this new event listener inside of your onclick and after you append it to your .body div.

Example:

let d = document.querySelector(".lop");
let body = document.querySelector(".body");

d.addEventListener("click", function () {
  let c = document.createElement("p");
  c.appendChild(document.createTextNode("lopas"));
  body.appendChild(c);


  document.querySelector("p").addEventListener("click", function () {
    console.log("Hi");
  });
});

As requested, here is how you could just split some of this out to be its own methods for clarity. Feel free to use your own style as its just an example:

const onClickLop = (e) => {
  const el = document.createElement("p");
  const bodyDiv = document.querySelector(".body");

  el.appendChild(document.createTextNode("lopas"));
  bodyDiv.appendChild(el);


  el.addEventListener("click", onClickLopas);
};

const onClickLopas = (e) => {
    console.log("Hi");
});


document.querySelector(".lop").addEventListener("click", onClickLop);

about 4 years ago · Juan Pablo Isaza Relatório

0

The code to add the event listener for the p element is executing before your code that creates it. Move the event handler into the first function so that it isn't triggered until the element is created and added to the document. However, that will mean that each time you click the first element, a new p will be created with its own handler (separate question/answer).

Also, by doing that you can consolidate some code.

let d = document.querySelector(".lop");
let body = document.querySelector(".body");

d.addEventListener("click", function () {
  let c = document.createElement("p");
  c.appendChild(document.createTextNode("lopas"));
 
  c.addEventListener("click", function () {
    console.log("Hi");
  });
  
  body.appendChild(c);

});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="lop">s</div>
    <div class="body"></div>

    <script src="script.js"></script>
  </body>
</html>

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