Home > other >  Printing HTML element on console returning NULL (javascript)
Printing HTML element on console returning NULL (javascript)

Time:11-15

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?

CodePudding user response:

Just edit your Home.js like this.

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

test();
<p id="cart1">
  hello world
</p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
}

CodePudding user response:

I think you should do console.log(cart1.innerHTML);

  • Related