Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

244
Views
Printing HTML element on console returning NULL (javascript)
function test(){
  let cart1 = document.getElementById('cart1');
  console.log(cart1);
}

I have created a test function to print the contents inside a <p> tag on to the console.

And this is my HTML.

<body> 
  <p id="cart1">
    hello world
  </p>
  <script src="home.js"></script>
</body>
</html>

But this is what gets printed on the console:

null

Why is this happening?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Just edit your Home.js like this.

function test() {
  let cart1 = document.getElementById('cart1');
  console.log(cart1);
}

test();
<p id="cart1">
  hello world
</p>

about 4 years ago · Juan Pablo Isaza Report

0

Please replace your JS code with the following. You've to use innerHTML property to get the text inside from p tag. The innerHTML property sets or returns the HTML content (inner HTML) of an element.

test();

function test(){
  let cart1 = document.getElementById('cart1').innerHTML;
  console.log(cart1);
}
about 4 years ago · Juan Pablo Isaza Report

0

I can't reproduce this problem, I wrote a simple example, and it works fine.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
  <p id="cart1">hello world</p>
</body>
<script type="text/javascript">
    function test() {
      let cart1 = document.getElementById('cart1');
      console.log(cart1);
    }
    test();
</script>
</html>

If he still has problems, I suggest using the onload event.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
  <p id="cart1">hello world</p>
</body>
<script type="text/javascript">
    window.onload = () => {
       let cart1 = document.getElementById('cart1');
      console.log(cart1);
    }
</script>
</html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!