Search code examples
javascriptjqueryhtmlarrayshref

How change all the href with a specific url?


I want to change all the urls of the href = "" that are in my home page, but it is a specific url.

Example:

<a href="mydomain.com/issues/resolve"> The issue </a>

Switch to:

<a href = "mydomain.com/issues/resolve/#thecontent">The issue</a>

I clarify that there is more than one with the same url, I want to change them all.

I have tried this without any visible result this I am doing with javascript:

$enlaces = document.getElementsByTagName("a");

                  for (let i = 0; i < $enlaces.length; i++) {
                    $enlaces2 = $enlaces[i];

                    if ($enlaces[i].href == 'mydomain.com/issues/resolve') {
                        this.href = 'mydomain.com/issues/resolve/#thecontent';
                    }

                    console.log ($enlaces2);

                  }

Solution

  • An <a> node has many properties.

    Given:

    • HTML: <a href="https://www.example.com:80/this/is/the/path?foo=bar&bish=bash#myAnchor" >test link</a>,
    • javascript member representing the resulting DOM node: link,

    then the properties of interest here are:

    • link.href https://www.example.com:80/this/is/the/path?foo=bar&bish=bash#testSector
    • link.hostname www.example.com
    • link.pathname /this/is/the/path
    • link.hash myAnchor

    These and other properties are read/write.

    So from the question, you appear to want to test a.hostname + a.pathname. If so then the following will do what you want:

    $('a').each(function() {
        if ((this.hostname + this.pathname) == 'mydomain.com/issues/resolve') {
            this.hash = 'thecontent';
        }
    });
    

    You should see why testing the .href property didn't work.

    Notes:

    • reading: a.hash returns a string including the leading #
    • writing: a.hash = "someString" does not require the hash.
    • there were historical differences between browsers in this regard but I think they are ironed out now (worth testing).