Javascript -根据类名选择div元素并在其中添加图像



let output = document.getElementsByClassName("one");
const img = document.createElement("img");
img.src = "https://www.gravatar.com/avatar/4581a99fa5793feaeff38d989a1524c6?s=48&d=identicon&r=PG";
img.width = "25px";
document.output[0].appendChild(img);
.one {
border: 2px solid red;
}
<div class="one">Test</div>

上面的代码给出了一个错误Uncaught TypeError: Cannot read properties of undefined (reading '0')

您需要引用output[0],而不是document.output[0]

另外,您需要将图像width=""属性设置为25,而不是25px

let output = document.getElementsByClassName("one");
const img = document.createElement("img");
img.src = "https://www.gravatar.com/avatar/4581a99fa5793feaeff38d989a1524c6?s=48&d=identicon&r=PG";
img.width = "25";
output[0].appendChild(img);
.one {
border: 2px solid red;
}
<div class="one">Test</div>

相关内容

  • 没有找到相关文章

最新更新