pavlos163
pavlos163

Reputation: 2890

Javascript .css("font-weight") change of behaviour

I have a Javascript method to check if an element has a bold font-weight.

function selected(element) {
    return element.css("font-weight") === "bold";
}

This used to work but recently I realised that it has stopped working.

Even though in inspection, the element's CSS is identical to before:

<td title="Example" style="font-weight: bold; color: black;">EXAMPLE</td>

The above function returns false.

That is because, element.css("font-weight") returns a number instead (700).

I have changed my function to:

function selected(element) {
    return element.css("font-weight") === "bold" || element.css("font-weight") === "700";
}

And it works. Anyone knows why? I am using Chrome 62.0.3202.94, does that play a role?

Upvotes: 1

Views: 733

Answers (3)

erikvimz
erikvimz

Reputation: 5476

This is a jQuery thing. Apparently the .css() function checks for computed CSS styles.

(function () {
  var el = document.getElementById('el');
  $('#val0').html(window.getComputedStyle(el, null).getPropertyValue("font-weight"));
  $('#val1').html(el.style.fontWeight);
  $('#val2').html($('#el').css("font-weight"));
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="el" style="font-weight: bold;">EXAMPLE</span>
<p>
  Value of font-weight in plain Javascript: <span id="val1"></span>
</p>
<p>
  Value of computed font-weight in plain Javascript: <span id="val0"></span>
</p>
<p>
  Value of font-weight in jQuery: <span id="val2"></span>
</p>

Similar question jquery get css property font-weight returning number instead of 'bold' in IE .

Upvotes: 1

Emanuele Miani
Emanuele Miani

Reputation: 51

You could also use element.style.fontWeight to access that property to keep using === "bold"

Upvotes: 1

Deepak Kamat
Deepak Kamat

Reputation: 1980

Because the names bolder, bold, normal all maps up to the numerical values for the weight of the fonts. There are more possible numerical values than literal names in CSS thus jQuery returns the numerical value instead of the names of the weight.

I would suggest you remove the check for === "bold" at all because it is never going to return that value.

Check this: http://htmldog.com/references/css/properties/font-weight/

Upvotes: 1

Related Questions