Skip to content Skip to sidebar Skip to footer

Use Javascript To Get Url Of The Page And Use It In A Link

I have looked and looked for an answer to this question. So I apologize in advance when the solution is very easy. I want to take the url of the current page eg. www.example.com/ex

Solution 1:

Name your element with an ID, like: <a id="pageLink"></a> and then when the document loads you can run this snippet:

var link = document.getElementById("pageLink");
link.setAttribute("href", window.location.href);

Or, with something like jQuery:

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

EDIT In response to your question in the comments:

I'm not sure I'm understanding you completely but if it's fixed, then you'd simply concatenate to the href before setting it, e.g.

$("#pageLink").attr("href", staticUrl + window.location.href);

Solution 2:

I think you have to use window.location.href. I'm no JS expert, so let me know if it worked.

Solution 3:

You can give this a try:

<a href="" onclick="window.location.href=document.URL">same url link</a>

you can keep the href empty and just use the onclick event.

Hope this helps.

Solution 4:

You can use this in href (it's global object) but you can in onclick.

<aonclick="this.setAttribute('href', location);this.setAttribute('onclick', '');">foo</a>

It clear onclick so you get this only once so you can follow the link if you click it again.

Solution 5:

you can use document.location.href to find the address of the current page

<aid="cool-link">click it!</a><script>jQuery('#cool-link').attr('href', document.location.href)
</script>

Post a Comment for "Use Javascript To Get Url Of The Page And Use It In A Link"