Rahul Arora Rahul Arora - 1 year ago 98
Javascript Question

Jquery vs Javascript: getting css style object shows different result

I have the following code:

In my html

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

In my css

font-size: 16px;
color: #333333;

When in console I do


it gives: ""

but when I do


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?

Answer Source

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");

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download