繁体   English   中英

Javascript - Select div 元素按其 class 名称并在其中添加图像

[英]Javascript - Select div element by its class name and add an image in it

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM