Modifying a CSS property with jQuery

If I have the following HTML, how can I dynamically adjust the width of all "thinger" divs?

...
<div class="thinger">...</div>
<div class="thinger">...</div>
<div class="thinger">...</div>
...

One way to do this is using jQuery like so:

$(".thinger").css("width",someWidth);

But is there a way to achieve the desired result without inline styles and instead utilize CSS classes?

...
<style>
    .thinger {
        width: 50px;
    }
</style>
...
<div class="thinger">...</div>
<div class="thinger">...</div>
<div class="thinger">...</div>
...

I couldn't find a jQuery method dedicated to updating existing CSS classes. Does such a utility exist or should I opt for manually adding the styles using vanilla JavaScript as shown below:

var styleElement = document.createElement('style');
styleElement.type = "text/css";
styleElement.innerHTML = ".thinger {width:" + maxWidth + ";}";
document.getElementsByTagName('head')[0].appendChild(styleElement);

What are the pros and cons of each approach in terms of browser compatibility and adherence to best practices?

Answer №1

To efficiently apply styling to elements, it is recommended to create a separate CSS stylesheet and define class rules there. Simply add the class to the desired elements in your HTML code for easy maintenance and code reuse.

If you are unsure of the width of an element before runtime, using the css() method as you currently are is the most suitable approach.

Answer №3

Great question! It would be interesting to compare the performance benefits of different approaches.

$("<style>.thinger{width:" + maxWidth + ";}</style>").appendTo("head");

Instead of constantly adding new style tags to the page, it's better to update the existing one when needed. Here's an example:

http://jsfiddle.net/daniellmb/0u6rrwsq/

$('button').click(function(e) {
    // get the dynamic width setting
    var maxWidth = $(e.target).text(),
        newRule = '.thinger{width:' + maxWidth + ';}',
        styleTag = $('#thinger-style');

    if (styleTag.length) {
        // update existing tag
        styleTag.text(newRule);
    } else {
        // create new tag
        $('<style id="thinger-style">' + newRule + '</style>').appendTo("head");
    }
});

Answer №4

A simple way to manipulate classes and CSS properties in jQuery is by using the .addClass() and .removeClass() methods. This allows you to easily add or remove classes from elements.

$('#myDiv').addClass('newClass');

Alternatively, you can remove a class like this:

$('#myDiv').removeClass('oldClass');

If you need to update specific CSS properties, you can also use the .css() method. For example:

$('.newClass').css('color', 'red');

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

What is the best way to capture source code and store it in a text file?

Can you assist me in extracting the source code of a webpage and saving it into a text file? My goal: Instead of going through the process of right-clicking on the page, selecting view source code, copying, and pasting into a text file... I want to simpl ...

Get a numerical value from a JSON object

Attempting to retrieve information from an API, but encountering an issue due to a numeric property name. The method for accessing the data is as follows: Success: data[i].price_usd Unsuccessful Attempt: data[i].24h_volume_usd Have experimented with ...

Connection to mongo is currently unavailable for Middleware next

This code snippet shows a middleware for Next, which is designed to read the subdomain and check if it exists in the database. import { getValidSubdomain } from '@/lib/getValidSubdomain'; import { NextResponse } from 'next/server' impor ...

The alignment between the view and controller in Salesforce (Visualforce) is not effectively synchronized

Currently, I am utilizing a visualforce page to input scores for a series of questions. Within the controller, there is a map that stores these values and then saves them to the Database once the save button is pressed. However, upon clicking the button f ...

Cypress is having trouble loading a particular URL

I'm encountering a timeout error while trying to load a specific URL using Cypress. Even after setting the page load time to 2 minutes, the issue persists. Interestingly, general URLs like https://www.google.co.nz/ load without any problems. it(' ...

Troubleshooting React on an Apache Server: A Comprehensive Guide

An interactive React application utilizing React Router has been successfully deployed on an Apache server. After making modifications to the .htaccess file, most of the routes function correctly as intended. Some specific routes within the app rely on us ...

Tips on displaying a message when search results are not found

import React, { useState, useEffect } from 'react' import axios from 'axios' function DataApi({ searchTerm }) { const [users, setUsers] = useState([]) const [loading, setLoading] = useState(false) const [error, setError] = useSta ...

endless cycle when utilizing useEffect with a mandatory function

I'm currently in the process of creating a custom hook for sorting and filtering tables within a dashboard application. However, I am encountering an issue with an infinite loop when attempting to refetch data after changing sort or filter fields. The ...

Perform a series of clicks

I'm attempting to click a button multiple times. After each click, the button takes 1 second to load, then reappears and can be clicked again. My goal is to click this button a total of 5 times. for(i=0;i<5;i++) $('.class').click(); ...

TypeScript error: Unable to locate namespace 'ng'

I am attempting to utilize a tsconfig.json file in order to avoid having /// <reference tags at the beginning of multiple files. However, I keep encountering this error: [ts] Cannot find namespace 'ng'. any Here is my configuration within ...

Iterate through a JavaScript array to access objects with varying IDs

Struggling to navigate the JSON data due to ID 29450 and 3000 out of a total of 1500 IDs in the database. Looking to log the information ['Id', 'Description', 'StartDate'] for both IDs. Feeling a bit stuck, hoping someone can ...

Tips for utilizing Vue.js techniques to assign values to data properties

As a newcomer to Vue.js, I am in the process of learning how to display data retrieved from a server. In my new Vue app, I have defined a method: methods: { getData: function() { // making a request, parsing the response and pushing it to the array. ...

executing functions that return a JSX component within the render method

In an effort to enhance readability, I am striving to condense the length of the render() method by utilizing class methods that contain isolated JSX elements. A snag arises when attempting to apply this technique to more than one JSX element. Despite en ...

Dynamically assigning column values based on object properties

I am currently utilizing the Ionic Framework along with its grid system that is reminiscent of Bootstrap. However, I believe my query leans more towards AngularJS than specific Ionic components. Here is what I have: <ion-col *ngFor="let col of row ...

Choose all checkboxes across the entire webpage

Given the code below: <input type="checkbox" name="categories[9507]"> Is there a way to write a JavaScript command that can automatically select all checkboxes with similar naming structures on the entire page? The only difference in the names is t ...

JavaScript validation for a form dynamically generated within a table

NOTE: Utilizing Foundation 6 along with the Abide Form Validation. I'm currently working on implementing automatic form validation for a website. The approach I've taken involves creating a table (using the jQuery Datatables library) with multip ...

Determine if the password is accurate using jQuery

Having some trouble with my login form. The JavaScript code always returns a false value, even when I'm entering the correct username and password. This is the jQuery code snippet: $(document).ready(function(){ var teamname = $("#teamname"); var te ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

Restricting Checkbox Choices with JavaScript by Leveraging the forEach Function

I am developing a checklist application that limits the user to selecting a maximum of three checkboxes. I have implemented a function to prevent users from checking more than three boxes, but it is not working as expected. The function detects when an ite ...

Issue arising with data exchange between components using data service in Angular 5

Utilizing data service to share information between components has presented a challenge for me. References: Angular: Updating UI from child component to parent component Methods for Sharing Data Between Angular Components Despite attempting the logic o ...