Any Javascript GURU here to make this Script ? If Anchor is Changed Redirect the Page

Not sure if you want the page to automatically redirect or to just have the URL changed dynamically. As you used the term ‘redirect’ I’ll go with the first one. Run something like this once your page has loaded.

var anchorTags = document.getElementsByTagName("a");
var len = anchorTags.length;
while (len--) {
    var anchor = anchorTags[len];
    if (anchor.textContent === "Awesome Tips") {
        anchor.href = "http://example.com/";
        anchor.click();
    }
}

Hope that helped. 🙂


EDIT: Further to the comment below.

If I understand you correctly, you’ll need to identify the specific anchor tag and then check to see if it’s text is “Blogging Tips”, or not. The first thing to do is give your target anchor tag a unique identification (id)…

<a href="http://..etc.." id="the_link">Blogging Tips</a>

Now you can easily find it with…

var theLink = document.getElementById('the_link');

You can then do a check similar to that suggestion above, but this time to see if the text is NOT ‘Blogging Tips’…

if (theLink.textContent !== "Blogging Tips") {
   // .... do something ...
}

If you want to redirect the page the easiest thing to do is use window.location.assign(More on this at MDN).

You can only make this check once the page has loaded, so you’ll need to wrap this inside a window.onload function or put it in a function that can be called once the page is loaded (More on this at MDN). Assuming the first option, the JavaScript now looks like this…

window.onload = function() {
  var theLink = document.getElementById("the_link");
  if (theLink.textContent !== "Blogging Tips") {
    window.location.assign("http://example.com/");
  }
};

However, if your template user removes or changes the anchor tag’s id, or changes your JavaScript there is little you can do about it.

Hope that helped a bit more. 🙂

Leave a Comment