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;
}
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>