Solution 1 :


window.location.href = "www.blabla.com";

// or

window.location.href = "/mysite/some-page";

Solution 2 :

This won’t work here because this code is inside iframe, use it in your main document it will work there.

let playButton = document.getElementsByClassName("play-now-button")[0];
playButton.onclick = function(e) {
   window.location.assign('https://www/google.com')
}
<button class="play-now-button">Open Another Link</button>

Solution 3 :

this will be the HTMLButtonElement when the handler is executed.

You need to make a small change to your code.

playButton.onclick = function() {
window.location.href = "www.google.com"
}

Problem :

I have this button like so:

<button type="button" class="play-now-button" onclick="location.href='www.yahoo.com'">Play Now</button>

however, I’d like to change the value of location.href using vanilla js. What I have below isn’t working. I looked online and saw some suggestions but to no avail. What am I doing wrong?

let playButton = document.getElementsByClassName("play-now-button")[0];
playButton.onclick.location.href = "www.google.com";

I’ve also tried:

playButton.onclick = function() {
   this.location.href = "www.google.com"
}

But none of those work. I need to use the button. I don’t want to use an <a> tag because I want to maintain the styling. I’ve also tried to nest an a tag inside the button but also to no avail.

What am I doing wrong and how can I fix this?

Comments

Comment posted by Yan

so you want that on click of the playbutton it redirect you to google.com

By