lwinkyawmyat
lwinkyawmyat

Reputation: 1242

How i get external CSS value From external JS file?

I wanna to get element background value from javascript file. I has three files -

  1. html.html
  2. css.css
  3. js.js

html.html

<!DOCTYPE html>
<html>
<head>
    <title> I'm Button! </title>
    <link rel="stylesheet" type="text/css" href="css.css"/>
    <script type="text/javascript" src="js.js"></script>
</head>
<body>
    <div class="myBlock" onclick="heyJS()"></div>

</body>
</html>

css.css

.myBlock {
  width: 300px; max-width: 100%;
  height: 100px; max-height: 100%;
  margin: 0 auto; margin-top: 100px; 
  font-size: 50px; font-weight: lighter; font-style: normal; text-align: center;
  line-height: 100px; position: relative;
  background-color: #83DF31;
}

js.js

function heyJS() {
    alert(document.getElementsByClassName('myBlock')[0].style.backgroundColor);
}

After running the scrpit,I only get blank alert box.

How can i get div background value ?

Upvotes: 1

Views: 499

Answers (2)

Zee
Zee

Reputation: 8488

You can replace your alert() with this

alert(window.getComputedStyle(document.getElementById('myBlock')).backgroundColor);

or

alert(window.getComputedStyle(document.getElementsByClassName('myBlock')[0]).backgroundColor);

And modify your html a little bit if you using the first one.

<div id="myBlock" class="myBlock" onclick="heyJS()"></div>

Upvotes: 3

Shaggy
Shaggy

Reputation: 6796

Try the following:

window.getComputedStyle(document.querySelector(".myblock")).getPropertyValue("background-color");

Upvotes: 1

Related Questions