Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
How can I create one button to change the color of a text and then back to the default color?

I have this code here that I used to create two buttons to change the color (purple) and the other one to change it back to the default color (black). But I want to create only one button that does both, change the color, and then back to the default color in this case black. How can I do that? Thanks!

<body>
<h1>Welcome to my first Web App!</h1>

<p>This web app will change the color of the text below:</p>
<h3 id="color-change">My color will change!</h3>
<button onclick="changeColor()">Change color</button>
<button onclick="defaultColor()">Default color</button>

<script !src="">
    function changeColor(){
        var element = document.getElementById("color-change");
        element.className = "myClass";
    }

    function defaultColor(){
        var element = document.getElementById("color-change");
        element.className = "defaultCol";
    }
</script>
</body>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use .toggle() to toggle the class on the button click. What we do is get the classList of the element and toggle myClass on each click

var element = document.getElementById("color-change");
element.classList.toggle('myClass');

function changeColor() {
  var element = document.getElementById("color-change");
  element.classList.toggle('myClass')
}
.myClass {
  color: red;
}
<h1>Welcome to my first Web App!</h1>

<p>This web app will change the color of the text below:</p>
<h3 id="color-change">My color will change!</h3>
<button onclick="changeColor()">Toggle color</button>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda