Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to delete one letter at each click of the backspace key

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>
like image 205
ahmed Ali Avatar asked Jan 26 '23 06:01

ahmed Ali


1 Answers

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

like image 184
Andre Nuechter Avatar answered Jan 29 '23 10:01

Andre Nuechter