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

1 - 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>

3 - 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.

4 - How to Steps

4.1 - 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 }

4.2 - 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>

4.3 - Retrieve the elements with Javascript

Get all P element


allP = document.querySelectorAll("p");

4.4 - 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'));

4.5 - Result


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap