Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/413.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript将图像附加到标题_Javascript_Jquery_Html - Fatal编程技术网

使用javascript将图像附加到标题

使用javascript将图像附加到标题,javascript,jquery,html,Javascript,Jquery,Html,我有一个有h2标题的div。我想在标题中添加一个图像。这是我尝试过的,但是我得到了错误uncaughttypeerror:cannotreadproperty'style'为null。我做错了什么 var h2 = document.getElementById('Five0 h2'); var imgLogo = document.createElement("img"); imgLogo.setAttribute('src', 'my-image.png'); imgLogo.se

我有一个有h2标题的div。我想在标题中添加一个图像。这是我尝试过的,但是我得到了错误uncaughttypeerror:cannotreadproperty'style'为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);

这段代码没有错。您的问题在代码的其他地方,而不是这里。HTML元素的ID是Five0 h2吗?ID不能有空格。它不是id,而是选择器。。。hm@MarcoBonelli这是在这段代码上,因为当我拿出这段代码时,它运行良好。请包含所有Javascript代码和HTML结构。最好是修改属性而不是属性:imgLogo.src='my-image.png';imgLogo.id=imgLogo;。您应该使用querySelector而不是getElementById。感谢您的建议,非常感谢!