How to add image to button via Javascript?

Henry picture Henry · Mar 2, 2016 · Viewed 39k times · Source

I am trying to add image to buttons I have using Javascript but I can't seem to get it working. I have sucessfully added image using HTML5, however, for my needs I need to add the image via javascript.

Below is what I have written to add images via HTML.

<button class="button" id="Ok"><img src="images/ok.png"></button>

Below is what I have tried to add image via Javascript but it doesn't seem to work.

var buttons = document.getElementsByClassName("button");
for (var b = 0; b < buttons.length; b++) {
      buttons[b].src = "images\ok.png";   
  }

I am not to sure what I am doing wrong, any help would be nice. Thanks.

Answer

MGB C picture MGB C · Mar 2, 2016

I don't know if this is what you need..

<button id="button"></button>

<script type="text/javascript">
    var buttons = document.getElementById("button");
    buttons.innerHTML = '<img src="images\ok.png" />';
</script>