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>
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>
Share
Improve this question
edited Mar 5, 2020 at 0:01
Błażej Michalik
5,10645 silver badges64 bronze badges
asked Mar 4, 2020 at 20:24
ahmed Aliahmed Ali
597 bronze badges
1
- Does this answer your question? JavaScript chop/slice/trim off last character in string – Heretic Monkey Commented Mar 5, 2020 at 0:08
1 Answer
Reset to default 10Instead of p.textContent-=e.key;
do p.textContent = p.textContent.slice(0, -1);
.