Search code examples
javascriptheightwidth

While creating img in JS, how can I set it's container size in JS?


I've set an img tag in my JavaScript file to be appended to it's wrapper tag, .wrapper, and I want the .wrapper's width and height to be set to the width and height of the img inside, created in JS, but this doesn't happen and I don't know why, I know I could've given these sizes in CSS but my goal is to use JS and kind of do that dynamically by reading the sizes of the img created.

Can somebody help me with that?

function main() {

    let imgWrapper = document.getElementsByClassName("wrapper").item(0) ;

    let image = document.createElement("img") ;


    image.src = "https://i.sstatic.net/XFRNl.png" ;

    imgWrapper.appendChild(image) ;

    imgWrapper.style.width = image.style.width ;

    imgWrapper.style.height = image.style.height ;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        .container{
            height: auto;
            /*background-color: #121212;*/
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .wrapper{
            background-color: blueviolet;
            position: relative;
        }
        .wrapper img{
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body onload="main()">
<div class="container">
    <div class="wrapper">
    </div>
</div>
</body>
</html>


Solution

  • You can't extract the image width and height like that. you can use naturalWidth and naturalHeight property to get Width and Height of a photo, not of a css style. also you may consider that these values are integers so you have to add an px or whatever size you need.

    Try to run this code, it's working for me:

    function main() {
    
        let imgWrapper = document.getElementsByClassName("wrapper")[0];
    
        let image = document.createElement("img") ;
    
    
        image.src = "https://i.sstatic.net/XFRNl.png" ;
        imgWrapper.style.width = image.naturalWidth  + "px";
    
        imgWrapper.style.height = image.naturalHeight + "px";
    
        imgWrapper.appendChild(image) ;
        
    }