0

i want to insert div into my DOM, and in this div i have a button. so i want to create eventListener to this appended button, but i don't know how? i tried this but now work...

    const newMovie = document.createElement("div");
    newMovie.innerHTML = `
    <div class="movie">
          <img src=${movie.image}/>
          <div>
            <h3>${movie.name}</h3>
            <span>Rating : ${movie.rating} / ${movie.date}</span>
            <button id="deleteBtn">Delete</button>
          </div>
    </div>
    `;
    allMovies.append(newMovie);
    const deleteBtn = document.querySelector('#deleteBtn');
    deleteBtn.addEventListener("click", () => {
      const exsistMovie = newMovie.remove();
      movies.splice(exsistMovie, 1);
      updateMovies();
    });

but if i change deleteBtn to newMovie it will work, but i dont want to delete by clicking on movie, just delete when i click on this button..

i want to insert element to this div

<div class="movies"></div>

and its my all html code

    <div class="header">
      <h1 class="logo">My Project</h1>
      <h5>Add Movie</h5>
    </div>
    <div class="formm">
      <div class="form">
        <div class="err">
          <h1>Error</h1>
          <p>You Entered Wrong Value..</p>
        </div>
        <h2>Add Your Movie</h2>
        <input type="text" placeholder="Name Of Movie" id="movie" />
        <input type="text" placeholder="image URL" id="image" />
        <input type="number" placeholder="Rating" id="rating" />
        <div class="btns">
          <button id="submit">Submit</button>
          <button id="cancel">Cancel</button>
        </div>
      </div>
    </div>
    <div class="movies"> </div>
Rawand
  • 47
  • 1
  • 1
  • 8
  • Could you share us some of your html code? – FLiotta Nov 01 '20 at 18:50
  • i added all Html codes bro.. – Rawand Nov 01 '20 at 19:02
  • It seems to be a problem with adding an event to a dynamic created element, check this related question: https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript – FLiotta Nov 01 '20 at 19:08
  • Sorry but you meant that i should write this? ``` document.getElementById('deleteBtn').addEventListener('click', () => { // something }) ``` – Rawand Nov 01 '20 at 19:13

2 Answers2

0

I am guessing allMovies is the div with the class "movies". So just try allMovies.appendChild(newMovie);

relevant
  • 14
  • 4
-1

How you defined allMovies in your javascript? What is allMovies? appendChild() is the correct method to add a child to a html element. If you want to use append(), you need to use jquery.

kadina
  • 5,042
  • 4
  • 42
  • 83