I’m trying to learn programming, and I code things to practice and for fun. I tried to code it where when I click a button the button the text turns red. It worked but when I tried to make it add an image it didn’t work.
Here’s what I tried
<button onclick="TurnRed()">Redify</button>
<script>
function TurnRed() {
let x = document.getElementById("Lorem");
x.style.color = "red";
var img = document.createElement("img");
img.src = /HTML_Code/Ispum.webp;
var src = document.getElementById("header");
src.appendChild(img);
<div id="header"></div>
}
</script>
2
Answers
img.src should be a string,and the string is a location of the image,in your question miss the quotation mark for the location,add it and have a try
You can do something like following:
img
element#header
element)See the following code for an explanation (for example, here I have added a google logo):
Note: Since you are using
webp
format, I would recommend checking browser compatibility here: https://caniuse.com/webpReferences:
img
elementappendChild
methodbutton
element