Search code examples
javascriptonloadonload-event

Anyway to change href of link with no id and no jquery?


I'm working with a client and I'm only allowed to use javascript (don't ask why as I have no idea). They don't have jquery setup and they don't want it (once again I have no idea why)

Anyways there is a link on the page that they want to change the href to on page load. Below is the link structure.

<a class="checkout_link" title="Checkout" href="current_url">Checkout</a>

I was wondering if there is any way to change the href on page load using basic javascript for the link above? If so how would I go about doing it?

Thanks


Solution

  • window.onload=function() {
      var links = document.links; // or document.getElementsByTagName("a");
      for (var i=0, n=links.length;i<n;i++) {
        if (links[i].className==="checkout_link" && links[i].title==="Checkout") {
          links[i].href="someotherurl.html";
          break; // remove this line if there are more than one checkout link
        }
      }
    }
    

    Update to include more ways to get at the link(s)

    document.querySelector("a.checkout_link"); // if no more than one
    document.querySelectorAll("a.checkout_link"); // if more than one
    

    to be even more selective:

    document.querySelector("a[title='Checkout'].checkout_link"); 
    

    Lastly newer browsers have a classList

    if (links[i].classList.contains("checkout_link") ...
    

    window.onload = function() {
      alert(document.querySelector("a[title='Checkout 2'].checkout_link").href);
    }
    <a href="x.html" class="checkout_link" title="Checkout 1" />Checkout 1</a>
    <a href="y.html" class="checkout_link" title="Checkout 2" />Checkout 2</a>