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

186
Views
¿Puedo cambiar la clase de un enlace de una clase a otra usando javascript?

He estado intentando usar la función js .toggle para cambiar la clase de un enlace para convertirlo de un color a otro al hacer clic.

 <html> <style> .the-button-inactive { display: inline-block; height: 20px; width: 20px; border-radius: 10px; background-color: black; } .the-button-active { display: inline-block; height: 20px; width: 20px; border-radius: 10px; background-color: blue; } </style> <body> <div class="the-button-container"> <a href="#the-image-1" id="the-image-1-id" onclick="myFunction()" class="the-button-inactive"></a> </div> <script> function myFunction() { var element = document.getElementByID("the-image-1-id"); element.classList.toggle("the-button-active"); } </script> </body> </html>

El enlace ya tiene la clase " the-button-inactive " y estoy tratando de cambiarlo a la clase " the-button-active " al hacer clic usando el script anterior, aunque no estoy seguro de por qué no funciona. El objetivo final sería lograr que el enlace cambie de color de negro a azul cuando se hace clic y luego de azul a negro nuevamente cuando se hace clic en otro enlace.

Hasta ahora, no sucede nada cuando se hace clic en el enlace.

Pude lograr esto anteriormente usando botones en lugar de enlaces, pero he decidido tratar de abordar este problema usando enlaces ahora.

Aquí está el jsfiddle que estoy usando para probar este script: https://jsfiddle.net/tqr2h4pb/

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

usted tenía un error tipográfico en su código. Cambie getElementByID a getElementById y funciona bien.

siempre debe verificar la consola para la depuración, dice Uncaught TypeError: document.getElementByID is not a function"

about 4 years ago · Juan Pablo Isaza Report

0

El método de alternar no afectará a las clases que ya existen, por lo que persiste .the-button-active.

HTML:

 <a href="#the-image-1" id="the-image-1-id" onclick="myFunction()" class="the-button-inactive">click</a>

JavaScript:

 function myFunction() { const element = document.querySelector("#the-image-1-id") element.classList.toggle("the-button-active") element.classList.toggle("the-button-inactive"); }

Esto funcionó para mí para alternar estados inactivos y activos

about 4 years ago · Juan Pablo Isaza 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!