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

322
Visualizações
Uncaught TypeError: Cannot read properties of null (reading 'appendChild')

I'm trying to insert a new Div and an img inside that div via JS. I made a Class that i will user later on with a function inside that should be called to use that function and insert the image. When doing this i constantly get Uncaught TypeError: Cannot read properties of null (reading 'appendChild') HTML and JS below:

<!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();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When you attempt to grab the 'newDiv' element by it's id it doesn't yet exist in the HTML document. You need to append the newDiv element to the page first and then you can retrieve it by it's 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); 

Also to make things more simple you could just do this...

 //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); 
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