4

I can't figure out how to get CSS parameter(proper term?) or values to display in things like a p with getElementById().innerHTML. I apologize but this is sort of two questions--when the CSS value is a number, do I need to use toString or something of that nature?

I would appreciate a pure JS answer, but jQuery is fine too if you think it is best. I am doing this on an app in my phone called HTML + CSS + Javascript--I don't know how one accesses the jQuery library.

HTML:

<body>
     <h1>Practice Page</h1>
    <div id="box">
        <div id="runner"></div>
    </div>
  <p id="color"></p>

  <p id="width"></p>

    <script src="practiceA.js" type="text/javascript"></script>

</body>
</html>

JS:

document.getElementById('color').innerHTML=
document.getElementById('runner').style.backgroundColor;

document.getElementById('width').innerHTML=
document.getElementById('box').style.width;

And the CSS:

#runner{
  height:10px;
  width:10px;
  background-color: red; 
}

#box{
   height:100px;
   width:100px;
   border:1px solid black;
}
shodak
  • 65
  • 10

1 Answers1

-1

You can't access CSS properties that were set from a CSS file using element.style . Instead you need to use getComputedStyle, but this can get messy with browser compatibility and what not, so I recommend using jQuery like below. (If you choose not to use jQuery, the answer I linked has a nice helper function that you could use)

jQuery example:

$('#color').html($('#runner').css('backgroundColor'));
#runner{
  height:10px;
  width:10px;
  background-color: red; 
}

#box{
   height:100px;
   width:100px;
   border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
<h1>Practice Page</h1>
<div id="box">
    <div id="runner"></div>
</div>
<p id="color">x</p>

<script src="practiceA.js" type="text/javascript"></script>

</body>
Community
  • 1
  • 1
libcthorne
  • 418
  • 3
  • 11
  • I thought this answered my question, and that the link to the duplicate did, but it didn't go as far as showing me how to display that number on the screen. I may have variables that are defined as the values I wanted, but I can't see them. And if I want to see them as innerHTML, do I need to use toString? As document.write, I would assume not? – shodak May 29 '16 at 00:18
  • Nevermind! Now I understand the jQuery. Still trying to see if it works, though... – shodak May 29 '16 at 00:25