Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 733
Dave Avatar asked Mar 07 '11 14:03

Dave


People also ask

How can the href for a hyperlink be changed using jQuery?

Answer: Use the jQuery . attr() Method attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

How do I change a link in href?

To set of modify the value of the href attribute of a link or the <a> tag, you can use the jQuery . attr() method. This method can also be used to get the value of any attribute.

Can a link have no href?

An a[href] element is a link (which is why they are matched with :link in css). links are clickable. An a element without the [href] attribute is otherwise just a placeholder for where a link might otherwise have been placed, and not clickable, nor are they in the tabbing order of the page.


1 Answers

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>
like image 194
mplungjan Avatar answered Oct 02 '22 12:10

mplungjan