Table of Contents

CSS - How to get an inline property with Javascript (font-size)

Description

This page will show you how to retrieve with Javascript an inline property value defined with the style attribute

The How to will retrieve the 20px of the font-size from the below HTML code

<p style="font-size: 20px">Foo bar</p>

Bird's-eye view solution

This howto will use the element.style object of a javascript element. This is where the inline style definition is stored.

If the property is defined in a style sheet, the property will not be present in the element.style object and will report an empty string.

How to Steps

Define a css stylesheet

We define a stylesheet to show that the value of element.style.fontSize is not defined in this case

.sheet { font-size: 15px }

Create the HTML page

<p style="font-size: 20px">A p element with the font-size defined inline</p>
<p class="sheet">A p element with the font-size defined by a stylesheet</p>

Retrieve the elements with Javascript

Get all P element

allP = document.querySelectorAll("p");

Output the value of element.style.fontSize for each element

console.log("The first p with an inline definition has a fontSize property of "+allP.item(0).style.fontSize);
console.log("The second p with a stylesheet definition has an undefined fontSize property "+(typeof allP.item(1).style.fontSize == 'undefined'));

Result