0

I want to insert an image into a div tag with the ID "window":

<div id="window">
        <h3 id="score">Score: 0</h3>
        <h3 id="end">End Game</h3>
        <video autoplay muted loop id="myVideo">
            <source src="images/background.mp4" type="video/mp4">
        </video>
    </div>

What my function looks like atm:

function spawn1() {
document.getElementById("window").innerHTML = "<img src='images/redtarget.png' style='width:10%'>";
}

How can I insert an HTML element without using .innerHTML since it replaces everything within my div tag?

bsb21
  • 45
  • 1
  • 8

3 Answers3

2

If you want to attach an image into your div you can do the following:

function spawn1() {
    let imageElement = document.createElement('img');
    imageElement.setAttribute('src','images/redtarget.png');
    imageElement.setAttribute('id', 'imageId');   //Use the id for a CSS selector to style it
    let windowDiv = document.getElementById("window");
    windowDiv.appendChild(imageElement);
  }
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
0

Simply concatenate existing html like bellow.

function spawn1() {
    document.getElementById("window").innerHTML = document.getElementById("window").innerHTML + "<img src='images/redtarget.png' style='width:10%'>";
}

Here is the jsfiddle link: https://jsfiddle.net/gpkquwz0/

Sarower Jahan
  • 1,445
  • 1
  • 13
  • 20
0
elem.innerHTML = elem.innerHTML + myNewStuff;
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24
  • 1
    Code-only answers are discouraged. Please provide an explanation why and how your answer solves the problem. – Igor F. Feb 12 '20 at 08:07
  • @IgorF.: Yes, code-only answers are discouraged. But they should still be reviewed as "Looks OK" in the Low Quality Posts queue. Reference: https://meta.stackoverflow.com/questions/260411/reviewing-low-quality-posts-answers-without-explanation – BDL Feb 12 '20 at 09:32