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

3

8

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

Objective answered 7/3, 2011 at 14:27 Comment(6)
It's possible using normal JavaScript of course, but it would be so much easier with jQuery - in addition to fetching the link (using getElementsByTagName() and searching the resulting array), you will want to do this onDOMLoad instead of onload... which needs additional code to work across browsers. jQuery or some other library would make this really easy.Scholarship
@Scholarship Apart from domload, I see no particular need for jQuery.Hippel
@Objective do you know the unique characteristics of the particular <a> that you wish to change?Nutpick
@Hippel well, if you want to grab the link using the class name, and you want to do this down to the last detail, you'd have to implement jQuery's .hasClass() that works for multiple classes (class="navigation checkout_link") which is also not completely trivial. But the OP may not need thatScholarship
@Scholarship i agree with you on using JS framework. It is easier to use .hasClass and ondomready provided by the frameworks, but i suppose special occassions like what the OP mentions would require vanilla JavaScript. But, yes ondomready is better way to go but it's alot easier just use JS frameworkNutpick
Unless management says "No Frameworks" :)Hippel
H
15
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>
Hippel answered 7/3, 2011 at 14:37 Comment(9)
kudos for the links collection, guess it's more efficient than my suggested getElementsByTagName("a") :)Raynaraynah
+1 Nice, didn't know about document.links. Two notes: This will work onload, i.e. when the document is fully loaded including images - which is usually notably later than when the DOM is loaded; and the class name needs to match perfectly, so no multiple classes allowed. If you can live with those restrictions, this is a very efficient methodScholarship
true - we can use links[i].className.indexof("checkout_link")!=-1 if there might be moreHippel
@Hippel that would give a false positive e.g. on checkout_link_bigger, though. Here's a nice regex: new RegExp('\\b' + classname + '\\b');Scholarship
My pragmatic side suggests that there are only one class. Or we can remove the className test and just match on title which my pragmatic side ALSO tells me is unique for the Checkout link(s)Hippel
@Hippel agreed. I just thought I'd mention it for future generations who may happen by and copy+pasteScholarship
This worked perfectly thanks a ton! I had no idea document.links even existed.Objective
:) It is a collection and exists since the dawn of time. Like document.images and document.formsHippel
Updated to include querySelectorHippel
N
0

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
            }
        }
    }
Nutpick answered 7/3, 2011 at 14:31 Comment(1)
Yes that would work, but I have no access to the html at all. So I can't add an id to the link. =/Objective
S
0

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.

Sidonia answered 7/3, 2011 at 14:35 Comment(1)
getElementsByTagName("*") is too expansive IMO, use getElementsByTagName("a") instead.Raynaraynah

© 2022 - 2024 — McMap. All rights reserved.