Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

247
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda