Search code examples
javascriptelementgetelementbyidgetelementsbytagnamegetelementsbyname

How do I get checkbox elements after of creating them with javascript and add some event on it?


I build a to do list like below but I can't get the input type=checkbox element after creating it and adding an event on it right down the my block code:

enter image description here

const getvalue = document.getElementById("add-work")
const btn = document.getElementById("btn")
const listcont = document.getElementById("listcont")

btn.addEventListener("click", e => {
  const eleme = document.createElement("p")
  const inpu = document.createElement("input")
  const tags = document.createElement("span")
  inpu.setAttribute("type", "checkbox")
  eleme.append(inpu)
  eleme.append(tags)
  tags.innerHTML += getvalue.value
  listcont.append(eleme)
  getvalue.value = ""
})


Solution

  • You can add an id to the input using:

    inpu.id = "yourid"
    

    and then access the element using getElementById later in any other file.

    Or add an event listener to it right away after creating it using

    inpu.addEventListener(...)