Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to do a to-do app. I want to select newly created P elements in order to add event listeners to them. However, how can I select them - I could try document.querySelector but it only select the first one. If I choose to use document.querySelectorAll, I cannot choose them by their index, because I want to choose them at random, not one by one, according to their order. I can't predict the index of an added element.
HTML
<div class="container">
  <h2>Put your items for your to-do list:</h2>
  <input type="text" class="myForm" onfocus="this.value=''" placeholder="Your items...">
  <button class="btn">Submit</button>
</div>



JavaScript
const myForm = document.querySelector(".myForm");
const myFormBtn = document.querySelector(".btn");
const container = document.querySelector(".container");
let myElement;


myFormBtn.addEventListener("click", function(){
  console.log(myForm.value);

  if( myForm.value != "") {
   let para = document.createElement("p");
   para.setAttribute("class", "myToDo")
   let node = document.createTextNode(`✏ ${myForm.value}`)
   myElement = para.appendChild(node);

  container.appendChild(para);
  myForm.value = "";
  }


  let itemCreated = document.querySelector(".myToDo")

  itemCreated.addEventListener("click", function (){
      this.style.backgroundColor = "red";
  })
})


What I have tried:

document.querySelectorAll but I don't know the index of the elements - they will be chosen at random and their number is not specified
Posted
Updated 14-Oct-22 3:55am
Comments
Member 15627495 14-Oct-22 4:39am    
why don't you add the event listener before append to the dom ?

Member 15627495 is correct, you don't need to wait until the new element has been added to the DOM before you add event listeners. By creating your new element you have immediate access to register the event listener as so:

JavaScript
let para = document.createElement("p");

para.addEventListener('click', () => {
  para.style.backgroundColor = 'red';
});
 
Share this answer
 
You could simplify this code by using event delegation[^]:
JavaScript
const myForm = document.querySelector(".myForm");
const myFormBtn = document.querySelector(".btn");
const container = document.querySelector(".container");

container.addEventListener("click", e => {
    let target = e.target;
    if (target.tagName !== "P") { target = target.closest("p"); }
    if (!target || !target.matches(".myToDo")) { return; }
    
    target.style.backgroundColor = "red";
});

myFormBtn.addEventListener("click", () => {
    console.log(myForm.value);
    if (myForm.value === "") { return; }
    
    const para = document.createElement("p");
    para.classList.add("myToDo");
    const node = document.createTextNode(`✏ ${myForm.value}`);
    para.appendChild(node);
    container.appendChild(para);
    myForm.value = "";
});
Demo[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900