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.

1
  • Always check your browser's console for errors. Commented Mar 29, 2021 at 7:54

1 Answer 1

-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

Sign up to request clarification or add additional context in comments.

4 Comments

"The script tag should always be before or after the </body> closing tag." this is wrong according to this tutorial. However, your solution worked. I guess it is the fact that the <p> has not been loaded.
@user171780 That is correct in some cases only because you can not do DOM Manipulation there. Read this: stackoverflow.com/questions/7452458/html-script-tag-placement
@user171780 If you want to know more about this read: stackoverflow.com/a/24070373/11171286
Thanks, your comments are very helpful. I am waiting the annoying StackOverflow timer to accept your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.