Jump to content

How do you use JS to get the ***effective*** style of an element?


Mike3456
 Share

Recommended Posts

I have been playing with document.getElementById("...").style to get styles of elements like a paragraph. But this thing returns only the inline styles. If a paragraph does not have an inline style with font-size then JS returns simply an empty string even though its font-size is set explicitly by an internal style font-size: 32px

 

How do you use JS to get the style that is actually used by a given element at a given moment?

 

 

 

 

 

================================

 

<!DOCTYPE html>
<html>
<head>
<style>

p#p1 {
font-size: 32px;
}
</style>
</head>
<body>

<p id="p1">Paragraph p1</p>
<p id="p2" style="font-size:16px">Paragraph p2</p>

<button type="button" onclick="myTest()">myTest()</button>

<br>
<br>

<script>
var x1 = document.getElementById("p1");
var x2 = document.getElementById("p2");

document.write("fontSize of p1: " + x1.style.fontSize + " (" + x1.style.fontSize.length + ")" + "<br>");
document.write("fontSize of p2: " + x2.style.fontSize + " (" + x2.style.fontSize.length + ")");

function myTest() {
var x1 = document.getElementById("p1");
var x2 = document.getElementById("p2");

alert("fontSize of p1: " + x1.style.fontSize + " (" + x1.style.fontSize.length + ")");
alert("fontSize of p2: " + x2.style.fontSize + " (" + x2.style.fontSize.length + ")");
}

</script>

</body>
</html>

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...