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

Handling multiple promises with JavaScript/Express Promise.all()

For my latest project, I am developing a movie discussion forum where users can create profiles and list their favorite films. To display the details of these movies, I have integrated the OMDB API with a backend route built using Express. In my initial t ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

Using Angular 2: A Beginner's Guide to Navigating with the Latest Angular 2.0.0-rc.1 Router

As I embarked on a new Angular 2 project, I was puzzled to discover that I inadvertently installed two different versions of the angular router: "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", Despite my best efforts, I co ...

Wordpress: The success and error functions in ajaxSubmit options are failing to trigger

jQuery 1.7.2 jQuery Validate 1.1.0 jQuery Form 3.18 Wordpress 3.4.2 In my current coding environment with the jQuery libraries mentioned above, I'm facing an issue with the jQuery Form JS: I've adapted the code for ajaxSubmit from the developer ...

Can someone please help me convert this jQuery code into vanilla JavaScript?

My Cordova app has an email sending function that utilizes jQuery. During debugging, the ajax function works perfectly in my browser, but once I build the app and test it on my phone, it stops working. I encountered a similar issue before, which was resolv ...

Tips for calculating the total of an array's values

I am seeking a straightforward explanation on how to achieve the following task. I have an array of objects: const data = [ { "_id": "63613c9d1298c1c70e4be684", "NameFood": "Coca", "c ...

Tips for choosing all elements in a form that have a specific class assigned

I am attempting to target all fields in a form with a specific class name and then select all the remaining fields. This is my form: <form style="margin:20px 0" id="myform_2"> <p> Query Name : <input i ...

printing on the internet without the hassle of a print window appearing

Looking for a way to print in web without displaying the print dialog, I came across an interesting solution. However, it requires installing Download & install WebClientPrint for PHP. Is there a method to achieve this without the need for third-party ...

How jQuery stops the submission of a form

Sample HTML Code <p><select name="status" class="form-control" id="showThisItem"> <option value=""> Select Status </option> <option value="Paid"> Paid </option> <option value="Unpa ...

execute numerous queries simultaneously

I have a task of creating a bridge (script) that connects two databases, Mongo and Oracle. First, I execute three find queries on my MONGO database from three different collections: Collection 1 = [{ name: 'Toto', from: 'Momo', ...

Creating multiple objects using a single object in JavaScript can be achieved by using the concept of object

When presented with the following data structure: { "time_1": 20, "time_2": 10, "time_3": 40, "time_4": 30 } and expecting a result in this format: [ { "key1": "time_1" ...

"Receiving a rendered HTML page instead of an SQL result from a jQuery POST request

Currently, I am utilizing codeigniter within my application and have implemented a jQuery post function that is performing flawlessly. $.post('getticketstacktype', {ticketnumber:ticketnumber},function(result) { alert(result); } Subsequently, I ...

displaying pictures exclusively from Amazon S3 bucket using JavaScript

Considering my situation, I have a large number of images stored in various folders within an Amazon S3 bucket. My goal is to create a slideshow for unregistered users without relying on databases or risking server performance issues due to high traffic. I ...

Utilize Jquery to create smooth animated scrolling within a specific div instead of the entire page

I am currently using an older script that utilizes jquery anchor links to animate the page to the anchor. While it is effective, I am looking to modify it to only animate the content of a specific div instead of the entire page. Are there any suggestions ...

Problem with see-through images against a see-through backdrop

I'm experiencing a strange issue with a graphic that has rounded corners. On my HTML page, I have the body set to transparent (style="filter:alpha(opacity=100);opacity:100;background-color:transparent;"), and within this body is a div containing a PN ...

Angular directive preventing default action but Chrome still loading image on drag

Has anyone encountered an issue with an angular directive that is not successfully preventing Chrome's default action? Below is the code for the directive in question: app.directive('fileDrag', function () { return { restrict: ' ...

The form submits immediately after jquery is activated

One challenge I'm facing involves multiple forms on a single page being submitted using jQuery. Currently, I have the following code snippet: $("form").submit(function (e) { // Submit form via Ajax }); The problem arises when the form is only s ...

Maintaining Proper Header Dimensions

Having some issues with aligning my fixed widget and floating navigation. The fixed widget is not respecting the height of the floating navigation and is appearing at the top when in its fixed position. I'm currently using "Q2W3 Fixed Widget" for the ...

What could be causing the issue with the functionality of third-level nested SortableJS drag-and-drop?

I am currently utilizing SortableJS to develop a drag-and-drop form builder that consists of three types/levels of draggable items: Sections, Questions, and Options. Sections can be dragged and reorganized amongst each other, Questions can be moved within ...

Are we looking at a declaration of an arrow function? Is this concept even real?

I have been exploring the concept of function expressions versus function declarations with arrow functions. From my understanding, this is an example of an arrow function expression: const fred = greeting = () => { console.log("Hello from arrow ...