Can I get a CSS image rule in JavaScript?

I want to get a css image rule like (URL, Size) in JavaScript like Variable.

Example Show:

- HTML right syntax:

<div id="mydiv"></div>

- The correct CSS syntax:

<style>
body{
background: url('a.png');
background-image-size: cover;
}
</style>

JS error syntax:

    <script>
      function GetImgVar(){
       var imgsrc = document.body.style.backgroundImage;
         document.getElementById('mydiv').style.backgroundImage=imgsrc;
       }
    </script>
+4
source share
1 answer

Yes, you can. Try:

<style id="stylesheet1">
body{
background: url('a.png');
background-image-size: cover;
}
</style>

<script>
var sheet = document.querySelector('#stylesheet1').sheet;

console.log(sheet.cssRules);// This will print all css rules that belongs to the body tag;

</script>
0
source

All Articles