1

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>
1
  • 1
    onclick should be a function, your setting it as a string Commented Jun 4, 2022 at 10:40

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.