0

currently I am making my own project and I got stuck in :/ I wanted to add an event and give some function on div which is made with a button("create"). However, the console returned "Uncaught TypeError: Cannot read property 'addEventListener' of null" this. I think it is because DIV(.c) is made after JS run. But I need to add an eventlistener and function on DIV(.c) to accomplish what I want. So, is there any way to bind a div which is created later and add an

const createButton = document.querySelector(".create");
const paperBook = document.querySelector(".b");

createButton.addEventListener("click", createWriting);

function createWriting(e) {
  e.preventDefault();
  const writing = document.createElement("div");
  writing.classList.add("c");
  writing.innerHTML = `All work No rest make jack a dull boy`;

  paperBook.appendChild(writing);
}

const myProblem = document.querySelector(".c");

myProblem.addEventListener("click", randomFunction);

function randomFunction(e) {
  e.preventDefault();
  console.log(e)
}
<div class="a">
      <button class="create">create</button>
      <div class="b"></div>
    </div>

event on it?

Below is my code. But I summarized it to simplify for you if you need a whole code just ask me, please :) thx!

geo
  • 821
  • 1
  • 8
  • 15
  • Does this answer your question? [Attach event to dynamic elements in javascript](https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript) – Jon P Jul 04 '21 at 22:58

1 Answers1

1

I think the problem is that this part of code

const myProblem = document.querySelector(".c");

It is executed before you create your .c element, so the new elements would not be included on it. Try to add the event everytime a new element is created in the createWriting function

const createButton = document.querySelector(".create");
const paperBook = document.querySelector(".b");

createButton.addEventListener("click", createWriting);

function createWriting(e) {
  e.preventDefault();
  const writing = document.createElement("div");
  writing.classList.add("c");
  writing.innerHTML = `All work No rest make jack a dull boy`;

  paperBook.appendChild(writing);

  writing.addEventListener("click", randomFunction);
}

function randomFunction(e) {
  e.preventDefault();
  console.log(e)
}
<div class="a">
   <button class="create">create</button>
   <div class="b"></div>
</div>
AlexSp3
  • 2,201
  • 2
  • 7
  • 24