skip to Main Content

I have Button A with href "www.A.com".
Im trying to figure out condition to achieve this:

If button’s href != "www.A.com", then function rewritte button’s href to "www.A.com".

I imagine whole function like this:

<script>
var x = document.getElementById("button A");
var y = "www.A.com";


window.onload = function() {
    if (x.href != y){
    document.getElementById("button A").href="www.A.com"; 
 }
}
</script>

Im kind of new to coding in JavaScript, so maybe I’m absolutely wrong.
Thanks for help.

2

Answers


  1. welcome to stack overflow, Your code looks almost correct, but the id shouldn’t have a space button A try to put it as buttonA

    and href returnning full url including http:// so you shoud make your y variable:

    var y = "http://www.A.com";
    

    and inside load function:
    document.getElementById("button A").href= y;

    Login or Signup to reply.
  2. You should not use any space in id, Try changing button A into buttonA

    Check out this, it may solve your problem.

    var x = document.getElementById("buttonA");
    var y = "https://www.A.com";
    
    window.onload = function(){
        if(x.href != y){
            x.href = y;
        }
    }
    <a id="buttonA" href="https://www.google.com">BUTTON</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search