0

I am learning HTML, CSS and JavaScript. Now I want to write the document title in a <p> tag and I wrote this HTML file:

<!DOCTYPE html>
<html>

<head>
    <title>HTML experimentation</title>
    <script>
        document.getElementById("document_title").innerHTML = document.title;
    </script>
</head>

<body>
    <p id="document_title">This text should be replaced by the title of the document</p>
</body>

</html>

According to the tutorials I find on the web, this should work. It does not. Why?

I have noted that if I do this:

<!DOCTYPE html>
<html>

<head>
    <title>HTML experimentation</title>
    
    <meta charset="utf-8">
    <script type="text/javascript"
        src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
    </script>
    <script type="text/x-mathjax-config">
        MathJax.Hub.Config({
            tex2jax: {
              inlineMath: [ ['$','$'], ["\\(","\\)"] ],
              processEscapes: true
            }
        });
        document.getElementById("document_title").innerHTML = document.title;
    </script>
</head>

<body>
    <p id="document_title">This text should be replaced by the title of the document</p>
</body>

</html>

it works. This, however, does not seem to be the way of making what I want.

Thomas
  • 150,847
  • 41
  • 308
  • 421
user171780
  • 514
  • 3
  • 10

1 Answers1

-1

The p tag has not been loaded when your script was executed.

The script tag should always be before or after the </body> closing tag.

<!DOCTYPE html>
<html>

<head>
  <title>HTML experimentation</title>
</head>

<body>
  <p id="document_title">This text should be replaced by the title of the document</p>

  <script>
    document.getElementById("document_title").innerHTML = document.title;
  </script>
</body>

</html>

Some useful resources

Manas Khandelwal
  • 3,006
  • 2
  • 8
  • 18
  • "The `script` tag should always be before or after the `

    ` closing tag." this is wrong according to [this tutorial](https://www.w3schools.com/js/js_whereto.asp). However, your solution worked. I guess it is the fact that the `

    ` has not been loaded.

    – user171780 Mar 29 '21 at 07:57
  • @user171780 That is correct in some cases only because you can not do DOM Manipulation there. Read this: https://stackoverflow.com/questions/7452458/html-script-tag-placement – Manas Khandelwal Mar 29 '21 at 08:02
  • @user171780 If you want to know more about this read: https://stackoverflow.com/a/24070373/11171286 – Manas Khandelwal Mar 29 '21 at 08:04
  • Thanks, your comments are very helpful. I am waiting the annoying StackOverflow timer to accept your answer. – user171780 Mar 29 '21 at 08:06