A sudden change in the behavior of Javascript's .css("font-weight") function

I recently encountered an issue with my Javascript method that checks for bold font-weight on an element.

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

Although the code used to work perfectly fine, it suddenly stopped working.

Upon inspecting the element, I noticed that its CSS remained unchanged:

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

Surprisingly, the function now returns false.

This is because element.css("font-weight") now returns a number (700).

To fix this issue, I updated my function to:

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

After making this change, it started working again. Can anyone explain why this was necessary? Could it be related to using Chrome 62.0.3202.94?

Answer №1

Due to the fact that the names bolder, bold, normal all correspond with numerical values representing the weight of fonts, jQuery returns the numerical value instead of the literal names in CSS. With a greater number of possible numerical values compared to literal names, this is the more reliable approach.

It is recommended to eliminate the check for === "bold" entirely, as it will never produce that specific value.

To learn more about font-weight properties in CSS, check out:

Answer №2

Another way to retrieve the font weight property is by using element.style.fontWeight instead of comparing it to "bold".

Answer №3

Here's an interesting jQuery tip. It seems that the .css() function actually looks 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>

Check out a related question on this topic here: jquery get css property font-weight returning number instead of 'bold' in IE.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interactive Video Effect

Seeking to create a unique video hover effect on an image where, when the mouse hovers over it, a video pops up similar to examples found on this website. I have been grappling with finding a solution for this issue over the past few months. Does anyone ...

Customizing date and time formats in ng-bootstrap for Angular applications

Seeking assistance in implementing ng-bootstrap datetimepicker instead of just a datepicker. This link shows separate date and time pickers, but I am looking for a combined datetimepicker. The desired format is: 2019-09-10 12:54:30.963852. Is there a met ...

Loading content synchronously

Could you assist me in finding a solution to synchronize the loading of pages and elements? Currently, my code looks like this: $(Element).load(File); ... other commands... window.onload = function () { Update_Elements(Class, Content); } Everything ...

Resizing columns in HTML table remains effective even after the page is refreshed

I've created HTML pages with tables that have multiple columns, but I'm experiencing an issue. The columns are not resizable until I refresh the page. Could someone assist me in fixing this problem and explaining why it's happening? ...

We could not find the requested command: nodejs-backend

As part of my latest project, I wanted to create a custom package that could streamline the initial setup process by using the npx command. Previously, I had success with a similar package created with node.js and inquirer. When running the following comma ...

Using the ampersand in Sass conditionals

I have some specific styling defined like this .activities { border: 1px solid green; .activity { background-color: red; &:first-child { background-color: yellow; } } } I am looking to style the .activity element that is a ...

A guide to resetting items directly from a dropdown select menu

I need help with clearing or resetting select options directly from the dropdown itself, without relying on an external button or the allowClear feature. Imagine if clicking a trash icon in the select option could reset all values: https://i.stack.imgur. ...

The complete function of jQuery animate() is triggered before the animation is finished

Upon scrolling to a specific element on the page, I want to assign a class to that element. However, the issue arises when the wrong element ends up receiving the class because the complete function is triggered before the scrolling animation has finished. ...

Tips for designing a webpage where a div element adjusts to fit the screen, regardless of the width of the content inside

Can CSS3 or a JavaScript library be used to create a webpage with a div that contains content wider than the screen, such as a large image or newsletter, and still fits it to the screen without scrolling or clipping any content? Below is an image demonst ...

Is there a different way to access a PHP page besides using a hyperlink? I've tried that method but it doesn't seem to

Within my side navbar, I have a dropdown menu with sub-menus for each option. My directory structure is as follows: RBS | +-- All php files are located here |--one.php |--two.php | +-- css | | | +-- all css files are stored here | + ...

Remove a batch of images from Amazon Web Services

Currently, this is the code snippet I am utilizing to delete multiple images from AWS: AWS.config.update({ accessKeyId: process.env.ACCESS_KEY, secretAccessKey: process.env.SECRET_ACCESS_KEY }) const s3 = new AWS.S3({ params: { Bucket: process. ...

Layering one div on top of another div

I have a vision of what I want: Here is the code I came up with: HTML <div class="main_container"> <div class="team1">team 1</div> <div class="vs">VS</div> <div class="team2">team 2</div> </div> CSS . ...

The text/font-weight of the header button is mysteriously shifting without warning

While creating a header for my webpage, I encountered an issue where the text family was changing when the dropdown menu was launched in Safari 8. Curiously, this behavior did not occur when using Chrome to launch the jQuery function. Even after attempting ...

Express encounters an undefined value in req.body

My current challenge involves fetching POST data to my node.js server running express. I made sure to configure the bodyparser before setting up the routes: const express = require('express'), bodyParser = require('body-parser'), app = ...

Incorporating the non-typescript npm package "pondjs" into Meteor applications using typescript files

Implementing the Pondjs library into my project seemed straightforward at first: meteor npm install --save pondjs However, I'm encountering difficulties when trying to integrate it with my Typescript files. The documentation suggests: In order ...

What approach is most effective for implementing a user-generated image uploading feature?

I am currently working with django and I have a requirement for users to upload images in their posts. However, I am unsure about the backend process for this. Should I create a database entry with the image URL, create a separate folder for each user, t ...

Tips for rearranging an item to the beginning of an array at index 0

What is the most efficient way to delete a specific object from an array and move it to the beginning? I have attempted using regular methods such as finding the index, manually splicing, and then moving the object to the top. farmer: [ { id:1, name: "na ...

The ultimate guide to resizing a div using radio buttons!

I've managed to create a functionality that allows for showing and hiding a div based on radio button selection. However, I am facing an issue where the main div grows infinitely when the "yes" option is clicked multiple times, and shrinks to nothing ...

Looking for a way to extract a dynamic URL from a website's div element?

Is there a way for my app to load dynamically by extracting and reading the changing URL from a webpage? //webpage <div style="display:none" id="urladdress"> //dynamic url **https://freeuk30.listen2myradio.co ...

Ways to switch the state of one element while causing other elements to respond

Here is the code snippet I am working with: function myFunction(x) { x.classList.toggle('change'); } body, hmtl { background- color: black; } .text { color: Black; } a { text-decoration: none; } .container { display: inline-block; ...