使用javascript将图像附加到标题

Appending an image to a heading using javascript

本文关键字:标题 图像 javascript 使用      更新时间:2023-09-26

所以,我有一个带有h2标题的div。我想在标题中添加一个图像。这是我尝试过的,但我得到了错误Uncaught TypeError: Cannot read property 'style' of null。我做错了什么?

 var h2 = document.getElementById('Five0 h2');
 var imgLogo = document.createElement("img");
 imgLogo.setAttribute('src', 'my-image.png');
 imgLogo.setAttribute("id", "imgLogo");
 h2.appendChild(imgLogo);

使用jQuery:获得

 var h2 = document.getElementById('Five0 > h2');
 var imgLogo = document.createElement("img");
 imgLogo.setAttribute('src', 'my-image.png');
 imgLogo.setAttribute("id", "imgLogo");
jQuery( "#Five0 h2" ).append(imgLogo);