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

191
Vistas
Replace onclick function of an object using Javascript

How do I replace the destination URL on a button when using onclick?

<div id="my_button" onclick="window.location.replace('/destination1')">Button<div>

So it would look like this

<div id="my_button" onclick="window.location.replace('/destination2')">Button<div>

The following Javascript code doesn't work though. Why?

<script>
document.getElementById("my_button").onclick="window.location.replace('/destination2')"
<script>
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

onclick that you have used in tag - is html event attribute, but onclick in tag, that you also tring to change - is div object property.

Both are like "onclick", but it's not the same.

So, if you want to make thing work, do this:

document.getElementById("my_button").onclick = () => window.location.replace('/destination2');

onclick div property need function(callback) not a string

about 4 years ago · Juan Pablo Isaza Denunciar

0

A simple way to do it would be by adding a listener and preventing the default behavior of the event

document
  .getElementById('my_button')
  .addEventListener('click', function (event) {
    event.preventDefault();
    window.location.replace('/destination2');
  });

working example

about 4 years ago · Juan Pablo Isaza Denunciar

0

element.onclick requires a function to be assigned and differs from the attribute <node onclick=""> where the content will be wrapped up in a function automatically.

If you want to change the attribute, make use of element.setAttribute("onclick", "...");

element.setAttribute("onclick", "window.location.replace('/destination2');");

Behaves similar to:

element.onclick = function() { window.location.replace('/destination2'); };

Another solution would be using the data-attributes which can be accessed by element.dataset.name.

Example:

<div id="my_button" data-path="/destination2" onclick="window.location.replace(this.dataset.path);">Button</div>

And to change it:

my_button.dataset.path = "/otherPath";
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