如何在HTML标记的开头附加图片?

时间:2015-05-12 12:44:40

标签: javascript html

我正在使用JavaScript。

我的HTML页面中有以下链接:

enter image description here

现在我想在文本开头之前附加绿色美元符号,而不是在它下面。我目前有以下代码:

var imgElement = document.createElement("img");
imgElement.setAttribute("src",server+"images/dollar-green.png");
anchor.appendChild(imgElement);

4 个答案:

答案 0 :(得分:2)

您需要使用insertBefore

anchor.insertBefore(imgElement);

答案 1 :(得分:0)

也许你应该试试insertBefore()。将您的代码的最后一行更改为:

anchor.insertBefore(imgElement, anchor.childNodes[0]);

然后在<img>标记上添加CSS代码:

img {
    float: left;
}

img {
    display: inline-block;
}

或通过JavaScript:

imgElement.setAttribute('style','float:left;');

答案 2 :(得分:0)

试试这个:

anchor.insertBefore(imgElement, anchor.childNodes[0])

答案 3 :(得分:0)

这样做的简单方法是在图像上使用float style属性

&#13;
&#13;
var anchor = document.getElementById('theAnchor');
var imgElement = document.createElement('img');
imgElement.setAttribute('src','http://www.easyicon.net/api/resize_png_new.php?id=139&size=32');
imgElement.setAttribute('style','float:left;');
anchor.appendChild(imgElement);
&#13;
<a id="theAnchor" style="font-weight:bold;font-family:Arial;font-size:26px;color:#ff0000;">
Sample Text
</a>
&#13;
&#13;
&#13;