Apply CSS styles to a group of elements retrieved from an object

How can I apply CSS properties to each element in a collection using jQuery?

const cssProperties = {
    "color": "#555555",
    "font-weight": "bold",
    "text-align": "left"
};

const $tdCollection = $("tr:first-child").find("td:nth-child(2)"); // Collection of <td> elements
$.each($tdCollection, function(index, element){
    $(element).css(cssProperties);
})

Answer №1

Avoid using the each() method here, and instead, apply the CSS properties directly to all elements in the jQuery collection:

let cssSettings = {
    "color": "#555555",
    "font-weight": "bold",
    "text-align": "left"
};

let $tdItems = $("tr:first-child").find("td:nth-child(2)");
$tdItems.css(cssSettings);

It's important to note that the variable storing the CSS rules is simply an object, not a JSON object, hence the name change.

Answer №2

If you want to style elements in a table using jQuery, you can utilize the for...in loop.

var jsonCss = {
  "color": "#555555",
  "font-weight": "bold",
  "text-align": "left"
};

var $tdCollection = $("tr:first-child").find("td:nth-child(2)");
for (var p in jsonCss) {
  $tdCollection.css(p, jsonCss[p]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr><td>Lorem</td><td>Lorem</td></tr>
</table>

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

Mastering the art of nested await functions in JavaScript

In my current Nodejs application using mongoose, I am implementing cache with MongoDB in-memory and MongoDB database. This setup is running on Nodejs 8.9 with async/await support enabled. let get_func = async(userId) => { let is_cached = await c ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

SQL AJAX Query Form

I have been searching for tutorials on how to create a good form with PHP and AJAX. I tried starting with a code given to me by a friend and managed to send the request successfully. However, it seems like the data I receive is empty. Could you please take ...

"Socket io Simplified: Embracing the Power of Drag

I'm currently in the process of developing a multiplayer card game using node, express, and socket io. However, I am facing some difficulties when it comes to transmitting drag and drop actions performed by one player to another connected player' ...

Creating a dynamic image viewing experience similar to Facebook's image viewer using jQuery

Here are two div tags that show the previous and next images from the large image collection: <div class="alignleft"><a href="1005.php"><img width="50" height="50" src="thumb-98.jpg" class="previous"></a></div> <div class ...

React Native not refreshing state data

I'm working with a FlatList that contains the code snippet below: <FlatList ........... refreshing={this.state.refresh} onRefresh={() => { this.setState({ ...

The React Native application is working fine on the emulator but is encountering some issues when trying

While the app runs smoothly on an emulator through Android Studio, I encounter an error when trying to run it from the CLI. error Failed to install the app. Ensure that you have set up the Android development environment properly: <a href="https://fac ...

What could be causing my website to extend beyond 100% width?

I've been working tirelessly on solving this issue for the past week, but unfortunately, I haven't had any luck finding a solution. The problem arose as I was designing a launch page for a program that my friend is developing. Despite setting the ...

Looking to transfer JSON data between JavaScript and Java code

I am dealing with a JSON string within my JavaScript code and I want to pass this information to a Java class. Can I simply use a regular Java class for this task or is it necessary to implement a servlet? Furthermore, I am curious about the process of pa ...

What are the steps for integrating DoctorJS with Emacs?

Is there a method to utilize DoctorJS (formerly known as jsctags) in order to create a TAGS file specifically for Emacs? I have been researching this topic and it appears that it typically defaults to the vi tags style, although I may be overlooking a str ...

What is the process for ordering by a many-to-many relationship in Sequelize?

I am dealing with a many-to-many relationship between User and Category, connected through the UserCategory model. Here is the code snippet illustrating this relationship: let user = await User.findAll({ where: { id: req.query.user }, attribut ...

Jest is throwing an error: Unable to access property from undefined while trying to import from a custom

I developed a package called @package/test. It functions perfectly when imported into a new, empty React TypeScript application. However, issues arise within Jest test suites. The usage of the CommonJS package version causes Jest to throw an error: Test ...

An inexplicable right margin

I am facing an issue with centering a table (a tracklist) under the album cover and title. There seems to be an unexpected margin on the right side that I can't seem to figure out. Any help in identifying the cause of this issue would be greatly appre ...

When there is an error or no matching HTTP method, Next.js API routes will provide a default response

Currently, I am diving into the world of API Routes in Next.js where each path is structured like this: import { NextApiRequest, NextApiResponse } from "next"; export default async (req: NextApiRequest, res: NextApiResponse) => { const { qu ...

Display link and popup box when hovering over an image!

Currently working on a web application with asp.net and telerik RadAjax control. I am looking to implement a functionality where, upon hovering over an image, a hyperlink should be displayed. Upon clicking the link, a new window should open (similar to c ...

Using jQuery's "data" method to deselect a checkbox is a simple and effective way to toggle its state

I am currently utilizing jQuery version 1.7.1 My objective is to access multiple items on a webpage that contain the microdata attribute "data-prodid". Although I've been advised to utilize jQuery's "data" property, I'm encountering issues ...

CSS - Divs failing to center using 'Auto: 0 Margin'

Attempting to design a menu bar using CSS, where the main buttons (blue divs) need to be centered within the navigation bar (orange divs) with equal spacing between each button. Despite trying margin: 0 auto, the alignment is not working as expected. Bel ...

Using a simulation to deactivate webpage elements and showcase the UpdateProgress control

I am currently attempting to disable certain page elements and display an update progress control in my application. In order to achieve this, I have applied a style sheet with the property filter: alpha(opacity=85); However, I encountered an error stati ...

Can jQuery effortlessly glide downward, come to a stop, continue downward, and then move upwards?

My webpage features a large table created and populated automatically every minute using ajax. The code structure is as follows: $(document).ready(function(){ setInterval(function(){ $.ajax({ //code to call backend, get the data, ...

What sets usePreloadedQuery apart from useQueryLoader?

I've been exploring graphQL and the react-relay library. These are the key points I've covered: Rendering Queries: where usePreloadedQuery is introduced. Fetching Queries for Render: where useQueryLoader is introduced. To keep it simple, I&apo ...