7

I would like to get my current URL address, save it to a variable and then pass it to an HTML element:

const url = document.URL;
document.getElementById("url").innerHTML = url;

I have tried using document.URL, window.location and window.location.href but none of them works for me. It displays nothing.

My HTML is:

<html>

<head>
  <script>
    const url = location.href;
    document.getElementById("url").innerHTML = url;

    function first() {
      console.log("It works!");
    }

    function submit() {
      let result;
      result = confirm("Would you like to confirm your change?");
      if (result == true)
        window.location = "okay.html";
      else if (result == false)
        console.log("You have clicked the \"cancel\" button.");
    }
  </script>
</head>

<body>
  <input type="button" onclick="first()" value="Try Me" />

  <p onmouseover="submit()">Hover over this text.</p>

  <p id="url">error</p>
</body>

</html>

5
  • 1
    location.href is fine. Did you try alerting it? Commented Sep 12, 2012 at 15:14
  • Show us the error message from the console. Does it say that document.getElementById("url") was null? Commented Sep 12, 2012 at 15:19
  • your JS code comes after the <p> or before? If before - the element doesn't exist when you executing the JS Commented Sep 12, 2012 at 15:19
  • 2
    This is probably a case of running the script before the element exists. Make sure your script is after you element with the id "url": jsfiddle.net/hu4Gq/1 Commented Sep 12, 2012 at 15:19
  • Thanks! That solved it. The problem was that my script was before my element. Commented Sep 12, 2012 at 15:25

3 Answers 3

7

Now that you have disclosed your entire code, we can see that you are running document.getElementById("url") too soon before the DOM is loaded. Move your script to the end of the body tag (see fixed code at the end of this answer).

Scripts that reference DOM elements cannot be run until those DOM elements are successfully loaded. There are three ways to ensure that.

  1. The simplest is to just place the script right before the </body> tag. Since things in the <body> tag are loaded sequentially, this ensures that all of your page has been loaded before the script runs and thus the script can reference it.

  2. You can code your script to wait for everything in the page to finish loading (including images) by running your code only when the window.onload event fires. This waits longer than necessary because it also waits for all images to finish loading, but it is safe and easy.

  3. You can code your script to wait until just the DOM is loaded. This is a little tricky to do cross browser since older browsers require different mechanisms. In newer browsers, this time is signified with a DOMContentLoaded event on the document.

window.location.href contains the current page URL. This always works and is the correct way to obtain the URL of the current page.

Working demo: http://jsfiddle.net/jfriend00/yGrxU/

If this doesn't work in your page, then you have something else wrong in your code. It could be because you are running your code too early before the DOM is loaded and thus document.getElementById() isn't working. You can fix that by moving your javascript code to the end of the body tag.

Another possibility is that you have a script error in your page that is stopping execution of your javscript. You should check the browser error console or the debug console to see if there are any script errors being reported.


Now that you've posted your entire code, we can see that you need to move the script to right before the </body> tag like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>

  <style type="text/css">

    input:hover
    {
        background: black;
        color: white;   
        border: 0;      
    }

  </style>


</head>

<body>

  <input type="button" onclick="first()" value="Try Me" />

  <p onmouseover="submit()">Hover over this text.</p>

  <p id="url">error</p>

  <script>   

  var url = location.href;
  document.getElementById("url").innerHTML = url;

  function first()
  {
    var string = "It works!";
    write(string);
  }

  function write(szoveg)
  {
      alert(szoveg);
  }

  function submit()
  {
      var result;
      result = confirm("Would you like to confirm your change?");
      if(result==true) 
          window.location="okay.html";
      else if(result==false)
          alert("You have clicked the \"cancel\" button.");

  }  

  </script>
</body>

</html>
Sign up to request clarification or add additional context in comments.

7 Comments

@MaxArt - I added another possibility.
I have tried alert - ing it, and it works that way. But I can't copy it's value to a variable, nor can I display it in an HTML paragraph.
@user1666226 - as you can see in the jsFiddle in my answer, it clearly works if used properly. There must be something else in your page that you have not disclosed causing it not to work. I would suggest showing us your entire page HTML/scripting. You also should look for any javscript errors that are stopping execution of your javascript.
may be he/she is not using window.onload event and the method is executed before the p tag is loaded?
@Sushil - I've already suggested in my answer how to address that page loaded issue.
|
3

Try this , you can botain the url of your page and put it into a variable

window.location.href

1 Comment

I posted at hte same time ok jfriend00
0

Your problem is that these two lines:

var url = location.href;
document.getElementById("url").innerHTML = url;

Execute before your <p> tag exists. Remove them from your script and add a new script after your p tag:

<p id="url"></p>
<script>
    var url = location.href;
    document.getElementById("url").innerHTML = url;
</script>

See this JSFiddle

It might be even nicer to use a script that replaces itself with a text node containing the url. Then you don't need to give the p an id if you don't use that id anywhere else:

<p>
    <script>
      (function(){
        var scripts = document.getElementsByTagName('script');
        var this_script = scripts[scripts.length - 1];
        this_script.parentNode.replaceChild(
          document.createTextNode(location.href),
          this_script
        );
      })();
    </script>
</p>

See this JSFiddle

1 Comment

Thanks! Though this node creating stuff is a bit high for me / for now. I am still a beginner in javascript :S :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.