How to get the current URL with JavaScript?

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>

Tags:

Javascript

Url