Add image element to an <a> tag

时间:2016-04-15 11:16:36

标签: javascript html image

I would like to add an image inside of a dynamically created link element using Javascript. Here is my code:

a.textContent = "My Link";
a.setAttribute('href', "#");

I would like the image to appear before the text in the link (My Link). In HTML, the resulting link would be:

<a href="#"><img src="foo.gif">My Link</a>

How can I do this?

2 个答案:

答案 0 :(得分:3)

您可以将insertAdjacentHTMLafterbegin

一起使用
a.insertAdjacentHTML("afterbegin", "<img src='foo.gif'>")

上面的代码将字符串提供的image元素作为h {{>}添加到目标锚元素中。

答案 1 :(得分:0)

<a href="#" id="testImage"></a>
$('#testImage').html('<img src="foo.gif">My Link');

使用此