5

How do I delete each letter the textcontent of a paragraph element at each keydown on the backspace key button like the input field remove one letter at time.

<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>repl.it</title>
      <link href="style.css" rel="stylesheet" type="text/css" />
   </head>
   <body>
      <p></p>
      <script>
         let p = document.querySelector("p")
         document.addEventListener("keydown",function(e){
           if(e.key === "Backspace"){
          p.textContent-=e.key;
         }else{
         p.textContent+=e.key
          }
          })

      </script>
   </body>
</html>
Błażej Michalik
  • 4,474
  • 40
  • 55
ahmed Ali
  • 59
  • 7
  • Does this answer your question? [JavaScript chop/slice/trim off last character in string](https://stackoverflow.com/questions/952924/javascript-chop-slice-trim-off-last-character-in-string) – Heretic Monkey Mar 05 '20 at 00:08

1 Answers1

10

Instead of p.textContent-=e.key; do p.textContent = p.textContent.slice(0, -1);.

Andre Nuechter
  • 2,141
  • 11
  • 19