-1

JS:

document.getElementById("terminal_text").innerHTML = "hello";

HTML:

<p id="terminal_text"></p>

<script type="text/javascript" src="js1.js"></script>

1st line inside js file. 2nd line and 3rd line(inside head) in html file.

I'm trying to use a javascript file to print to a paragraph tag using the ID and it's not printing. Any ideas? Thank you ! :)

millerbr
  • 2,951
  • 1
  • 14
  • 25
  • *"2nd line and 3rd line(inside head) in html file"* You can't put `p` elements in `head`; or rather, if you do, it terminates `head` and starts `body` implicitly (since the `` and `` tags are both optional in some situations). – T.J. Crowder Feb 28 '16 at 13:42
  • If line 3 comes before line 2 in the html file, this will happen as you are trying to get an ID that doesn't yet exist. Put line 3 in the body *after* line 2. – James Feb 28 '16 at 13:44
  • @T.J.Crowder Pretty sure the (inside head) is only applying to the script tag here – Joseph Young Feb 28 '16 at 13:46
  • But I've put the javascript into the Head tag? –  Feb 28 '16 at 13:46
  • 1
    You might need to do some tutorials on developing a web page. The `` is where your elements go, the `` is for information about the page such as title, scripts that are attached, etc – millerbr Feb 28 '16 at 13:50
  • Millerbr, I know where things go, Joseph has clarified that the script is the only thing that I've dropped into the head tag –  Feb 28 '16 at 13:52

2 Answers2

1

Put the script tag after your element in the body:

<body>
.. stuff

<p id="terminal_text"></p>
<script type="text/javascript" src="js1.js"></script>

.. more stuff
</body>
James
  • 20,957
  • 5
  • 26
  • 41
  • But what happens if I want to put more scripts that need to be run for other tags under that paragraph to be manipulated? thanks :) –  Feb 28 '16 at 13:50
  • @TingAli: Put them all at the end, just before the closing `

    ` tag.

    – T.J. Crowder Feb 28 '16 at 13:52
  • Just make sure that scripts that execute immediately are *after* all the tags they use. – James Feb 28 '16 at 13:52
  • It's a [long discussion](http://stackoverflow.com/questions/436411/where-is-the-best-place-to-put-script-tags-in-html-markup) where to put ` – Lux Feb 28 '16 at 13:53
0

You must place the <script> tag after the <p> tag, otherwise you <p> tag does not exist when your javascript code runs.

If you don't want to do this you can execute your code on the load event when your page is fully loaded:

window.addEventListener('load', function () {
  document.getElementById("terminal_text").innerHTML = "hello";
});
Lux
  • 17,835
  • 5
  • 43
  • 73