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?
答案 0 :(得分:3)
您可以将insertAdjacentHTML
与afterbegin
,
a.insertAdjacentHTML("afterbegin", "<img src='foo.gif'>")
上面的代码将将image
元素作为h {{>}添加到目标锚元素中。
答案 1 :(得分:0)
<a href="#" id="testImage"></a>
$('#testImage').html('<img src="foo.gif">My Link');
使用此