peace_love
peace_love

Reputation: 6471

How can I write the current url into an href attribute?

I found out how to write the current url into an element:

  <p id="example"></p>

    <script>
    document.getElementById("example").innerHTML = 
    window.location.href;
    </script>

My result is:

http://www.animalfriends.de/shop/

Now the difficult part is, that I have this link:

<a href="#top">Go to top</a>

and I want to get the current page url into the href before the #top and delete the last / so the result would look in the end like this:

<a id="gototop" href="http://www.animalfriends.de/shop#top">Go to top</a>

I tried something like this, but I am lost:

$(#gototop).attr('href', 'window.location.href;');

Maybe it is not possible?

Upvotes: 1

Views: 2085

Answers (1)

leroydev
leroydev

Reputation: 2945

With jQuery:

$("#gototop").attr("href", window.location.href);

With JavaScript:

document.getElementById("gototop").href = window.location.href;

If you'd like to add #top to the URL, just change window.location.href to window.location.href + "#top".

Why didn't your code work? So there's two reasons why the code below didn't work for you.

$(#gototop).attr('href', 'window.location.href;');
  1. The argument accepted by $() should be a string (or a variable containing a string). You didn't declare the #gototop variable. (on a sidenote, it's not possible to declare a variable with a name starting with #) You also didn't say it was a string (you'd need to surround it with single or double quotes, like "#gototop" or '#gototop'.
  2. window.location.href is a property (containing a string) within the window global variable. So you should pass it without single or double quotes, because else you're passing it as a string instead of a variable.

Upvotes: 4

Related Questions