Search code examples
javascripthtmlvariableshyperlinkhref

Javascript with if statement not changing href attribute


I set up a hyperlink whose href attribute needs to be changed by javascript, after an if statement, but it doesn't.

    <script>
    function addhttp(url) {

        var url = "newlink";

       if (!/^(f|ht)tps?:\/\//i.test(url)) {
          url = "http://" + url;
       }
       return url;
       document.getElementById('wl').href= url;
    };
    </script>

<li>
<a id="wl" href="oldlink">LINK</a>
</li>

Also a JSFiddle

What am I missing?


Solution

  • Two details were amiss. Firstly, as noticed by @Bjorn, the function isn't called which is fixed by replacing function addhttp(url) { ... }; with $(function () { ... });,
    and secondly, as @Mritunjay pointed out, the href is changed after the return is done so their order simply needs to be reversed to

    document.getElementById('wl').href= url;
    return url;
    

    Making the working script

    $(function () {
        var url = "new link";
    
       if (!/^(f|ht)tps?:\/\//i.test(url)) {
          url = "http://" + url;
       }
       document.getElementById('wl').href= url;
       return url;
    });
    

    If this answer helps you please upvote their comments instead.