Amanda
Amanda

Reputation: 12737

Why is "getElementsByTagName" not finding anything?

This seems like it should be pretty basic, and I can't figure out why it isn't working. I have a super simple page so far and I want to select the paragraphs with JS:

Here's my HTML:

<!DOCTYPE html>
<html>
  <head>
    <script src="misc.js" type="text/javascript"></script>
  </head>
  <body>
    <p id="first">Just one paragraph.</p>
    <p id="second">Two, actually.</p>
  </body>
</html>

And my JS:

var paras = document.getElementsByTagName('p');
console.log(paras.length);

I expect the console log to show 2 but I'm seeing 0. I read the documentation pretty closely and I can't figure out what I'm doing wrong here.

Upvotes: 1

Views: 813

Answers (1)

Quentin
Quentin

Reputation: 943214

At the time you run the script, there are no paragraphs in the document.

Either move the script element so it appears after the paragraphs, or put the code in a function and then call that function later (e.g. when the load event fires).

Upvotes: 5

Related Questions