Tom
Tom

Reputation: 3034

How can I get an element's font size with jQuery?

How can I get the actual font-size of the #t1 element? It is obviously 26px but in all the browsers I get 16px.

<div class="editor">Hello <span id="t1">my</span><br>dear <span id="t2">world</span></div>

<button id="test">TEST</button>

<style>
.editor
{
    font-size: 16px;
}
.editor:first-line
{
    font-size: 26px;
}
</style>

<script>
$('#test').click(function()
{
    alert( $('#t1').css('font-size') + ' vs ' + $('#t2').css('font-size') );    
});
</script>

Demo on JS Fiddle

Upvotes: 0

Views: 1921

Answers (2)

Nimish Mer
Nimish Mer

Reputation: 42

You wrote in your style:

.editor{
  font-size: 16px;
}

This line sets font-size to all its child tags thats why it always give 16

instead of

.editor:first-line{
  font-size: 26px;
}

This user needs to write

#t1{
  font-size: 26px;
}

it will give you the perfect size.

Upvotes: 1

Troy Thompson
Troy Thompson

Reputation: 371

The question here is - How to get style from a pseudo element.

var fontSize = window.getComputedStyle(
    document.querySelector('.editor'), ':first-line'
    ).getPropertyValue('font-size');

http://jsfiddle.net/troythompson/mrz3uh8x/

http://davidwalsh.name/pseudo-element

How do I access style properties of pseudo-elements with jQuery?

Upvotes: 1

Related Questions