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?
Simplemente edite su Home.js así.
function test() { let cart1 = document.getElementById('cart1'); console.log(cart1); } test(); <p id="cart1"> hello world </p>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); }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>