Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

245
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda