0

i have the html and css. i need to write a java function that places the same image 4 times into 4 identical divs and centers them.

function addTheImage() {
    var img = document.createElement('img');
    img.src = "https://media.giphy.com/media/27ppQUOxe7KlG/giphy.gif";
    document.body.appendChild(img);
}

here is the html and css for the site. the image needs to be in the tomato colored divs and not at the bottom of the page like it currently is

  • You need to add it to the div you want instead of the document, for example `document.getElementById('tomatoColoredDiv').appendChild(img);` – simdrouin Oct 30 '20 at 01:51

1 Answers1

0

First, just to clarify, you're writing JavaScript, not Java. (Easy mistake, but they're very different.)

Also, I don't see any HTML or CSS attached to your question – just that JS snippet. But, it shouldn't be too hard to add your image to multiple divs:

function addTheImage() {
    add_to_div('target1');
    add_to_div('target2');
    add_to_div('target3');
    add_to_div('target4');
}

function add_to_div(div_id) {
    var img = document.createElement('img');
    img.src = "https://media.giphy.com/media/27ppQUOxe7KlG/giphy.gif";
    
    var container = document.getElementById(div_id);
    container.appendChild(img);

}
.image-container {
  height: 50px;
  width: 100px;
  border: solid black 2px;
  text-align: center;
}
/* This selects all img tags inside image-container divs. */
.image-container img {
  height: 100%;
}
<div class="image-container" id="target1"></div>
<div class="image-container" id="target2"></div>
<div class="image-container" id="target3"></div>
<div class="image-container" id="target4"></div>

 <button onclick="addTheImage()">Adding the Images</button>
 
  

One issue you might be having:

document.createElement('img'); creates a single DOM node. You can't put a single DOM node more than one place – that's why I made a function to make a new one for each image-container.