Estoy tratando de insertar un nuevo Div y un img dentro de ese div a través de JS. Hice una clase que usaré más adelante con una función interna que debería llamarse para usar esa función e insertar la imagen. Al hacer esto, obtengo constantemente Uncaught TypeError: Cannot read properties of null (reading 'appendChild') HTML y JS a continuación:
<!DOCTYPE html> <html lang="en"> <meta charset="UTF-8"> <title>Actividad 3</title> <script type="text/javascript" src="actividad3.js"></script> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="style.css"> <body > <h2>EXTRAS DISPONIBLES</h2> </body> </html>JS
class extra { precio = "10€"; url = "concha_azul.jpeg"; constructor(precio, url) { this.precio = precio; this.url = url; } getHTML = function () { console.log("hello"); var newDiv = document.createElement("div"); newDiv.id = "x"; var div = document.getElementById("x"); var img = document.createElement("img"); img.src = "concha_azul.jpeg"; div.appendChild(img); } } let miExtra = new extra(); miExtra.getHTML();Cuando intenta tomar el elemento 'newDiv' por su id, aún no existe en el documento HTML. Primero debe agregar el elemento newDiv a la página y luego puede recuperarlo por su id ...
//Create new div var newDiv = document.createElement("div"); newDiv.id = "x"; //Add div to html body document.body.appendChild(newDiv); //Get new div by it's id var div = document.getElementById("x"); var img = document.createElement("img"); img.src = "concha_azul.jpeg"; div.appendChild(img);Además, para simplificar las cosas, podrías hacer esto...
//Create new div var newDiv = document.createElement("div"); newDiv.id = "x"; //Add div to html body document.body.appendChild(newDiv); //Add an image element to the div var img = document.createElement("img"); img.src = "concha_azul.jpeg"; newDiv.appendChild(img);