0

For your information, this is not a duplicate - my question was not solved by similar questions .

I am trying to log this element:

<p id="one">Test</p>

to the console with JavaScript:

var one = document.getElementById("one");
console.log(one);

However, this returns null for the console.log(one); line, and I can't figure out the reason. Where is the null value coming from, and how do I make it reference the <p id="one">Test</p> element?

EDIT: Full HTML code:

<!doctype html>

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>A tester</title>

        <script src="index.js"></script>

    </head>

    <body>

        <p id="one">One</p>

    </body>

</html>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79

3 Answers3

4

Probably you are accessing the element before the DOM is ready, Try with DOMContentLoaded:

document.addEventListener("DOMContentLoaded", function(event) {
  var one = document.getElementById("one");
  console.log(one);
})
<p id="one">Test</p>
Mamun
  • 66,969
  • 9
  • 47
  • 59
2

It is working fine :)

var one = document.getElementById("one");
console.log(one);
<p id="one">Test</p>
2

It works fine.

<html lang="en">

    <head>

        <meta charset="utf-8">

        <title>A tester</title>

        <script src="index.js"></script>
        <script>
            function getOne()
            {
                var one = document.getElementById("one");
                console.log(one);
            }
        </script>
    </head>

    <body onload="getOne()">

        <p id="one">One</p>

    </body>

</html>
The KNVB
  • 3,588
  • 3
  • 29
  • 54