使用javascript将图像附加到标题

时间:2014-10-21 17:23:53

标签: javascript jquery html

所以,我有一个带有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);

1 个答案:

答案 0 :(得分:0)

使用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);