Search code examples
javascripthtmlhref

Is it possible to change a href that is already defined


This is a very messy problem.

So I have an website. I do not have access to my server files. the only access i do have is through my Prestashop account which gives me limited access to change my website.

However Prestashop gives me a small module where I can enter in some of my own HTML / script code.

Basically I want to change an already declared href link. This href link is declared in the files on the server (which I do not have access to). Is there a way to change this already established href link via a script?

For example the word "contacts" on my websites links to my contacts page via a href such as this:

https://contacts.com/contacts.php"> contacts

But I want to add a script that will redirect that link to a different href such as this:

<a href = "https://contacts.com/contacts123456.php"> contacts </a>

I cannot seem to find this how to do this anywhere online. Can it be done?

I know the simplest thing to do is get into my server files and just cane the href from there to the new href value. However I do not have access to it.


Solution

  • If you already know the href is always going to be https://contacts.com/contacts.php, use querySelector with an attribute selector to find the element, then setAttribute to modify the value:

    document.querySelector("a[href='https://contacts.com/contacts.php']").setAttribute("href", "https://contacts.com/contacts123456.php");
    

    If there are multiple links with the exact same href, use querySelectorAll:

    document.querySelectorAll("a[href='https://contacts.com/contacts.php']").forEach(e => e.setAttribute("href", "https://contacts.com/contacts123456.php"));