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 and jQuery.

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

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>

0

2 Answers 2

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

Comments

-1

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.

2 Comments

Can you please fix to show p2 and p3? It's confuse me because Im so newb .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.