0
<div class="fruit" id="whole">
    <img class="fruit1" />
    <img class="fruit2" />
</div>
<script>
var img1=document.createElement("img");
    img1.src="http://us.yimg.com/i/us/nws/weather/gr/32ds.png";
    document.getElementById("whole").appendChild(img1);
</script>

I only know how to add <img> tag in the parent class, and output a image in it, like the code does.

However, I don't know how to output a image to the child class, i.e,"fruit1"

j08691
  • 204,283
  • 31
  • 260
  • 272
Freedom Gu
  • 61
  • 1
  • 2
  • 2
    An `` tag is a self closing tag that can't have any children, so you can't append another image to the image, the only thing you could do is change the source of the already existing image – adeneo Mar 08 '16 at 22:11
  • Then, how could I solve it. By using Node.append()? – Freedom Gu Mar 08 '16 at 22:15

1 Answers1

2

Are you trying to set the img src="" of .fruit1? If so you just need to set the src property after finding it

var fruit1image = document.getElementsByClassName("fruit1")[0];
fruit1image.src="http://us.yimg.com/i/us/nws/weather/gr/32ds.png";

Note that getElementsByClassName returns an array, so we need to grab the first (0th) element.

CaffGeek
  • 21,856
  • 17
  • 100
  • 184