Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
¿Cómo alternar el contenido de un elemento presionando una tecla?

Actualmente estoy tratando de hacer un sitio web donde si presiono q, la etiqueta p cambiará de "Q" a "A". Esto actualmente funciona con el siguiente código. Sin embargo, el problema es que al presionar q necesita volver a "A". Intenté hacerlo funcionar con removeEventListeners pero parece que no funciona.

 <script>
 document.addEventListener("keypress", event => {
 if (event.key == "q") {
 document.getElementById("P1").innerText = "Q"
 }
 });
</script>
almost 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Como @diegod sugirió en los comentarios, debe verificar qué carácter se muestra actualmente en el elemento p y cambiar el innerText consecuencia:

 const p1 = document.getElementById("P1");

document.addEventListener("keypress", event => {
 if (event.key == "q") {
 if (p1.innerText == "A") {
 p1.innerText = "Q";
 } else {
 p1.innerText = "A";
 }
 }
});

Usando el ejemplo del operador ternario :

 const p1 = document.getElementById("P1");

document.addEventListener("keypress", event => {
 if (event.key == "q") {
 p1.innerText = p1.innerText == "A" ? "Q" : "A";
 }
});
almost 4 years ago · Santiago Trujillo Report

0


const $ = (prop) => document.querySelector(prop)

const changeToQ = () => {
 $('p').innerText = 'Q'
}

const reset = () => {
 $('p').innerText = 'A'
}

document.addEventListener('keydown', (e) => {
 if (e.key === 'q') changeToQ()
})

document.addEventListener('keyup', (e) => {
 if (e.key === 'q') reset()
})

creo que esto es lo que buscas

almost 4 years ago · Santiago Trujillo Report

0

has intentado hacer otra declaración

 else{ document.getElementById("P1").innerText = "A"}
almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!