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

249
Views
Imprimir elemento HTML en la consola que devuelve NULL (javascript)
function test(){ let cart1 = document.getElementById('cart1'); console.log(cart1); }

Creé una función de prueba para imprimir el contenido dentro de una etiqueta <p> en la consola.

Y este es mi HTML.

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

Pero esto es lo que se imprime en la consola:

nulo

¿Por qué está pasando esto?

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

0

Simplemente edite su Home.js así.

 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

Reemplace su código JS con lo siguiente. Debe usar la propiedad innerHTML para obtener el texto dentro de la etiqueta p. La propiedad innerHTML establece o devuelve el contenido HTML (HTML interno) de un elemento.

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

0

No puedo reproducir este problema, escribí un ejemplo simple y funciona bien.

 <!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>

Si todavía tiene problemas, sugiero usar el evento onload .

 <!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!