1

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 ?

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank brother,why not working in alert(window.getComputedStyle(document.getElementsByClassName('myBlock')).backgroundColor);
Well, good question :) But I guess it is defined in that way. You will find more about it here developer.mozilla.org/en-US/docs/Web/API/Window/…
1

Try the following:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.