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?

4
  • it's document.getElementById("window").append('<img src="images/redtarget.png" style="width:10%">') & you might use createElement rather than having the image-element as a string Commented Feb 12, 2020 at 5:43
  • 1
    @admcfajn are you sure it's document.getElementById("window").innerHTML.append ? Commented Feb 12, 2020 at 5:45
  • Thanks @AbhishekPandey it's been a long day! Commented Feb 12, 2020 at 5:46
  • Does this answer your question? Adding HTML elements with JavaScript Commented Feb 12, 2020 at 5:48

3 Answers 3

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);
  }
Sign up to request clarification or add additional context in comments.

Comments

1
elem.innerHTML = elem.innerHTML + myNewStuff;

2 Comments

Code-only answers are discouraged. Please provide an explanation why and how your answer solves the problem.
@IgorF.: Yes, code-only answers are discouraged. But they should still be reviewed as "Looks OK" in the Low Quality Posts queue. Reference: meta.stackoverflow.com/questions/260411/…
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/

1 Comment

why don't to store innerHTML in a var instead of writing it again and again

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.