我正试图通过JS插入一个新的div和一个img。我创建了一个类,我将在稍后使用其中的一个函数,应该调用该函数并插入图像。当这样做时,我不断得到Uncaught TypeError: Cannot read properties of null (reading 'appendChild')
HTML和JS如下:
<!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();
当您尝试通过'newDiv'元素的id抓取它时,它还不存在于HTML文档中。你需要先将newDiv元素附加到页面上然后你可以通过它的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);
为了使事情更简单,你可以这样做…
//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);