0

I dont know why this code is not working! why is it showing the alert blank?

<html lang="en">

    <head>
        <title>Document</title>
        <style>
            #dd{
                height: 300px;
                width: 300px;
                background-color: mediumblue;
                color: white;
            }

        </style>
    </head>

    <body>
        <label>Color </label><input id="in1" type="text">
        <hr>

        <div id="dd">
    </div>

        <script>
            var colorTextBox = document.getElementById("in1");
            var div = document.getElementById("dd");

            div.onclick = function(){
                colorTextBox.value = div.style.backgroundColor;
        alert(div.style.backgroundColor);
            }

        </script>
       
    </body>
</html>

when the div is clicked the background color of the div should be written inside the input box and also shown in the alert.

  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+css+property+is+empty) of [why javascript this.style\[property\] return an empty string?](https://stackoverflow.com/q/9444751/4642212). – Sebastian Simon Mar 20 '21 at 14:49

2 Answers2

0

Have this, it will compute the rgb color: `

    var colorTextBox = document.getElementById("in1");
                var div = document.getElementById("dd");

                div.onclick = function(){
                    //colorTextBox.value = div.style.backgroundColor;
            //alert(div.style.backgroundColor);
            
            const element = document.querySelector('#dd');
            const style = getComputedStyle(element)
            var color= style.backgroundColor;
            alert(color);
                }
    <html lang="en">

        <head>
            <title>Document</title>
            <style>
                #dd{
                    height: 300px;
                    width: 300px;
                    background-color: mediumblue;
                    color: white;
                }

            </style>
        </head>

        <body>
            <label>Color </label><input id="in1" type="text">
            <hr>

            <div id="dd">
        </div>

            <script>
                
            </script>
           
        </body>
    </html>

`

MSQ
  • 489
  • 5
  • 15
0

Element.style.<style> can only retrieve styles if it's inline.

For example, if you changed the div to be <div id="dd" style="background-color: mediumblue">, then div.style.backgroundColor will return mediumblue.

To get the background-color as defined in your style tag, you should use getComputedStyle(Element) instead. getComputedStyle(div).backgroundColor does work, returning rgb(0, 0, 205), which is the rgb value for mediumblue.

Demo

jdabtieu
  • 534
  • 5
  • 20