skip to Main Content

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


  1. img.src = "/HTML_Code/Ispum.webp";
    

    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

    Login or Signup to reply.
  2. You can do something like following:

    • Create a img element
    • Add src attribute
    • Append the img element to desired html element (here #header element)

    See the following code for an explanation (for example, here I have added a google logo):

    function TurnRed() {
      let x = document.getElementById("Lorem");
      x.style.color = "red";
      var img = document.createElement("img");
      img.src = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
      var src = document.getElementById("header");
      src.appendChild(img);
    }
    <button id="Lorem" onclick="TurnRed()">Redify</button>
    <div id="header">
    </div>

    Note: Since you are using webp format, I would recommend checking browser compatibility here: https://caniuse.com/webp

    References:

    img element

    appendChild method

    button element

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search