How to set the height of a picture

function creatOneSnow(){
    var leftX = Math.random()*window.innerWidth;
    var topY = Math.random()*window.innerHeight;
    var snowDiv = document.createElement("div");
    snowDiv.style.position = "fixed";
    snowDiv.style.left = leftX + "px";
    snowDiv.style.top = topY + "px";
    snowDiv.innerHTML = "<img src="image/snow.png" width="20px"  />";
    document.body.appendChild(snowDiv);
}
The js above works correctly, and I want to set the width for the image element independently.

the test failed. Excuse me, how should I write it?

function createOneSnow(){
    var leftX = Math.random()*window.innerWidth;
    var topY = Math.random()*window.innerHeight;
    var snowDiv = document.createElement("div");
    snowDiv.style.position = "fixed";
    snowDiv.style.left = leftX + "px";
    snowDiv.style.top = topY + "px";
    snowDiv.innerHTML = "<img src="image/snow.png" id="myImg" />";
    var targetImg = document.getElementById("myImg");
    targetImg.style.width = "20px"; 
    document.body.appendChild(snowDiv);
}

how do I modify it?

Mar.11,2021

add a id :

to img
        var targetImg=document.getElementById('targetImg');
        targetImg.style.width= '20px'; 

  function createOneSnow(){
    var leftX = Math.random()*window.innerWidth;
    var topY = Math.random()*window.innerHeight;
    var snowDiv = document.createElement("div");
    snowDiv.style.position = "fixed";
    snowDiv.style.left = leftX + "px";
    snowDiv.style.top = topY + "px";
    var targetImg= document.createElement("img");
    targetImg.src = 'image/snow.png'; 
    targetImg.style.width = '20px'; 
    snowDiv.appendChild(targetImg);
    document.body.appendChild(snowDiv);
}

you can try this
if you modify it for later convenience, I suggest you write this

.
/**
 imgWidth --Number
*/
 function createOneSnow(imgWidth){
    var leftX = Math.random()*window.innerWidth;
    var topY = Math.random()*window.innerHeight;
    var snowDiv = document.createElement("div");
    snowDiv.style.position = "fixed";
    snowDiv.style.left = leftX + "px";
    snowDiv.style.top = topY + "px";
    var targetImg= document.createElement("img");
    targetImg.src = 'image/snow.png'; 
    targetImg.style.width = imgWidth + 'px'; 
    snowDiv.appendChild(targetImg);
    document.body.appendChild(snowDiv);
}

  

does not understand what you are trying to say. If you just want to set the width of each picture separately, such as img1 width=20px img2 width=20px, then you should use xsf_1991 .
if you want to set a different width for each picture, that is, the width of each picture is not manually set, you can write targetImg.style.width= Math.random () * 100 + 'px';

on the basis of xsf_1991.
Menu