我正在尝试通过JS在该Div中插入一个新的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();
发布于 2021-10-21 10:11:24
当你试图通过“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);
https://stackoverflow.com/questions/69659899
复制相似问题