Table of Contents

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

  • with an inline style
<p style="font-size: 20px">A p element with the font-size defined inline</p>
  • with a class defined in the sylesheet
<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

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

Result