2

I have the following code:

In my html

<h1 id="heading">My Site</h1>

In my css

#heading{
   font-size: 16px;
   color: #333333;
}

When in console I do

document.getElementById("heading").style.fontSize

it gives: ""

but when I do

$("#heading").css("fontSize")

it gives: 16px

Even if I print the whole style object, vanilla javascript shows all blank values but jquery shows correct results.

Why is there a difference between the two?

Rahul Arora
  • 4,503
  • 1
  • 16
  • 24
  • 5
    Related http://stackoverflow.com/a/15195345/2887133 ---- http://stackoverflow.com/a/1955160/2887133 – DaniP Jun 17 '16 at 20:46
  • 1
    jquery is javascript, jquery is javascript, jquery is javascript....... if you ever wonder how jquery does something it's very easy to look it up! because all jquery is is a library around regular javascript functions. – Ryan Jun 17 '16 at 20:54

2 Answers2

5

Because jQuery's css function gives you the computed style, whereas Element.style.fontSize gives you only styles that have been applied inline. The vanilla equivalent to the jQuery code would be this:

var heading = document.getElementById("heading");
window.getComputedStyle(heading).getPropertyValue('font-size');

This will give you the actual font size of the element, after any CSS has been applied.

Matis Lepik
  • 1,140
  • 2
  • 9
  • 18
2
document.getElementById("heading").style.fontSize

Will only get styles that are set inline like:

<h1 id="heading" style="font-size:16px">My Site</h1>`

To get the styles set from a stylesheet use getComputedStyle:

window.getComputedStyle(document.getElementById("heading"), null).getPropertyValue("font-size");

With inline styling:

console.log(document.getElementById("heading").style.fontSize)
<h1 id="heading" style="font-size:16px">My Site</h1>

With stylesheet styling

console.log(window.getComputedStyle(document.getElementById("heading"), null).getPropertyValue("font-size"))
#heading{
   font-size: 16px;
   color: #333333;
}
<h1 id="heading">My Site</h1>
j08691
  • 204,283
  • 31
  • 260
  • 272