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

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

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 Denunciar

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 Denunciar

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 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