2

I insert css in 3 ways

  • Inline style (p1)
  • Internal style sheet (p2)
  • External style sheet (p3)

I want to get value of css in each by Javascript && Jquery . Please show me how .

I cant get the value of p2 , p3 in same way as p1 . What's wrong ?

Many thanks !

window.onload = abc();

function abc(){
 var p1 = document.getElementById('p1').style.height;
 document.getElementById('p1').innerHTML = p1;
 var p2 = document.getElementById('p2').style.width;
 document.getElementById('p2').innerHTML = p2;
 var p3 = document.getElementById('p3').style.height;
 document.getElementById('p3').innerHTML = p3;
}
#p3{
 width: 200px;
 height: 200px ; 
 background-color: aqua ;
}
<!DOCTYPE html>
<head>
<title>CSS Element output</title>
 
</head>
<body>
<H1>CSS output element property</H1>
 <div id="p1" style="height:50px;width:100px;">check p1</div>
 <div id="p2">check p2</div>
 <style>
  #p2{
   height:50px;
   width:400px;
   background-color: bisque
  }
 </style>
 <div id="p3">check p3</div>
 
</body>

**

strong text

**

batkhuat91
  • 23
  • 2
  • Possible duplicate of [How to get an HTML element's style values in javascript?](http://stackoverflow.com/questions/2664045/how-to-get-an-html-elements-style-values-in-javascript) – jmargolisvt Sep 10 '16 at 04:28

2 Answers2

0

When you use dot notation, you are asking for an attribute. Only the first element has a style attribute, so this is why only your first attempt works.

jmargolisvt
  • 5,722
  • 4
  • 29
  • 46
0

You can get value of style attributes using window.getComputedStyle(); and getPropertyValue(); Please see the sample code below for getting value of height for your element p2:

var element = document.getElementById('p2'),
    style = window.getComputedStyle(element),
    res = style.getPropertyValue('height');

alert(res);
Vishnu
  • 70
  • 1
  • 6