用javascript中的图像替换文本

时间:2019-05-29 12:55:19

标签: javascript image text replace

我正在寻找一种用javascript中的图像替换文本的方法,但我做不到,

例如文字:

<div><p class="YellowTxt">MyYellowTxt</p></div>
<div><p class="BlueTxt">MyBlueTxt</p></div>
<div><p class="GreenTxt">MyGreenTxt</p></div>

要拥有黄色,蓝色和绿色的图像。

1 个答案:

答案 0 :(得分:0)

使用innerHTML:

function replace() {
  var el = document.getElementsByClassName('YellowTxt')[0]
  el.innerHTML = '<img src="" alt="image"/>'
}
<div>
  <p class="YellowTxt">MyYellowTxt</p>
</div>
<div>
  <p class="BlueTxt">MyBlueTxt</p>
</div>
<div>
  <p class="GreenTxt">MyGreenTxt</p>
</div>

<hr />

<button onclick="replace()">Replace</button>