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

11.1k views Asked by At

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

3

There are 3 answers

9
mplungjan On BEST ANSWER
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>

1
KJYe.Name On

Here is the jsfiddle demo

You should use ondomready event, but it's abit tricky when it comes to coding it in vanilla(suggest using a JavaScript framework). So, as an alternative(not best way to achieve what you are attempting to do), is to use window load(based on your requirements). In the JavaScript we attach a function that change the href of the <a> after window load:

html:

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

JavaScript based off title being unique and also contains checkout_link in the class attribute:

    window.onload = function() {
        var tochange = document.getElementsByTagName('a');
        for (var i = 0; i < tochange.length; i++) {
            //checks for title match and also class name containment
            if (tochange[i].title == 'Checkout' && tochange[i].className.match('(^|\\s+)checkout_link(\\s+|$)')) {
                tochange[i].href = "http://www.google.com";
                break;  //break out of for loop once we find the element
            }
        }
    }
1
jackJoe On

you could get the object by its class name, check this link: http://snipplr.com/view/1696/get-elements-by-class-name/

and then use it to change the href.