Using jQuery to modify CSS properties in the propertyName

With jQuery v1.6.4,

I am attempting to dynamically format some objects.

Take a look at my code snippet:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){

    style = {'color':'#F30', 'font-size':'20px'};

    /* example:1 - not working */
    for(attr in style) $('.text').css({attr:style[attr]});

    /* example:2 -works */
    //$('.text').css({'color':style['color']}).css({'font-size':style['font-size']});

})
</script>
</head>
<body>
    <div class="text">This is the text.</div>
</body>
</html>

Why is example 1 not functioning as expected? Is there another method I should consider?

The Chrome console does not display any errors. The "style" object will be formatted as JSON, so I am looking to streamline the code rather than manually specifying each style like in the second example.

Your assistance is greatly appreciated.

Answer №1

$('.text').applyStyles(style);

The issue here lies in the fact that you've constructed a JavaScript literal object. This is similar to the JSON format used for passing parameters in the subsequent example. However, it won't function properly as it doesn't iterate over your object, rendering it appear erroneous. The effort has already been made, so simply apply the styles.

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

Personalizing the fileTemplate selection in FineUploader

My English is not the best, so apologies in advance. I'm struggling to customize the FineUploader FileTemplate option. I don't want to use fineUploaderBasic; I want total customization. Initially, I managed to hide the file name and size after a ...

Dynamically pass specific outputs from multiple SQL queries to a form

The query is functioning properly, returning a table with the associated data in rows. I am looking to have a button displayed with each row that triggers a function specific to that row when clicked. Currently, the function works manually by inputting the ...

Is there a way to modify the background color of a button once it has been clicked, specifically using JavaScript?

I am looking to change the background color of a button that I have clicked on in my code. Do I need to use loops and conditions for this task? I attempted to access the first index, but I am unsure how to change the background color of other buttons. l ...

Exploring jQuery selectors with a looping mechanism to trigger click events

Trying to figure out how to loop through numerical selector values in JQuery while utilizing an onClick event handler. Is this a chicken-or-egg situation or perhaps a closure issue? Any guidance would be appreciated. $("#q01").click(function() { cle ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

Toggle the visibility of a specific div based on the selection of the "other" radio button or checkbox

While my question may not be vastly different from others that have been asked before, it's the subtle nuances that are causing me some trouble. In essence, I am trying to toggle the visibility of a text input field used for specifying the "other" op ...

Using Express and Node.js to implement the Google Maps API

Currently working on creating a simple web application using the Google Maps API with express/node. At the moment, I have three main files that make up my project: server.js const express = require('express'); const bodyParser = require(' ...

Retrieve data from TypeScript file (.ts) and use it in an HTML document

Recently I started learning Typescript and HTML as I work on building an Angular2 application. At the moment, I have a TypeScript file that resembles the following structure: import {Http, Headers} from 'angular2/http'; import {Component} from & ...

Ways to efficiently display elements in a grid in real-time

Attempting to design a layout where each row consists of 3 cards using Bootstrap's Grid layout for responsiveness. The challenge lies in the fact that the card data is stored in JSON format, and the length of the JSON Object array may vary, leading t ...

Timepicker Bootstrapping

I've been searching for a time picker widget that works well with Bootstrap styling. The jdewit widget has a great style, but unfortunately it comes with a lot of bugs. I'm on a tight deadline for my project and don't have the time to deal w ...

An hour ago, the Python and Selenium code was functional, but now it has suddenly ceased to work

Hello to all fellow community members, I recently attempted to locate the next button in Google search, specifically on the bottom right corner. Here is the HTML code snippet that pertains to this: <td aria-level="3" class="d6cvqb" ...

Implementing a permanent class following an incident

Is it possible to dynamically add a class to an element when an event occurs rather than based on a condition? For example, I have a td that displays a variable. <td>{{myVar}}</td>//myVar=10 When the variable changes to myVar=15, I want to ad ...

Enhancing CSS and HTML: Increasing the Border Color of Dropdown Menus and Utilizing Multiple Words per Dropdown Item

CODE div.box { display: block; text-align: center; margin: auto; z-index: 5 } #navMenu { margin: 0; padding: 0; } #navMenu ul { margin: 0; padding: 0; line-height: 30px; } #navMenu li { margin: 0; padding: 0; list-style: none; float: left; positio ...

CSS: What's with the weird gray element appearing in Safari?

Does anyone have a solution for removing the grey layer (cf the image) in Safari? This issue does not occur in Chrome. The structure is as follows: <div class="class1"> <div class="class2"> <select> ... </selec ...

Ways to confirm the validation of radio buttons in a form and implement CSS

I am having trouble adding validation to a form with radio buttons displayed as labels. I want to show a red border around the radios/labels or outer div when a radio button hasn't been checked before the user submits the form. I have attempted this ...

What sets apart adding a row from adding a col-12 in Bootstrap 4?

I have a doubt that I'm trying to clarify, but unfortunately it's not mentioned in the Bootstrap 4 documentation. Can someone explain the difference between these two code snippets? <div class="container"> <div class="row"> < ...

Turning multiple .html files into a single csv using beautifulsoup

I am dealing with a situation where I have 13,000 html files stored in a folder and my goal is to consolidate all the data into a single csv file. Although I believe I have made progress in extracting the data, I am encountering challenges when it comes t ...

What could be causing my website's screen resolution to not fit properly on mobile devices?

Initially, the resolution perfectly matched the width of mobile devices. However, after changing the background image, for some reason, the width no longer fits the device length precisely. I've tried resetting to a point where the resolution was fine ...

What is the best way to utilize CSS to center an element in relation to the scroll bar?

For a group project, I successfully centered a div on a webpage. However, I ran into an issue where the website's contents are centered taking the scroll bar width into consideration. This means that the web page contents adjust to be centered without ...

Unable to convert data to a JSON string

I've created a tool for building dynamic tables: <div class="container"> <div class="row"> <div class="col"> <hr> <h3>Add your data</h3> <button id="addTd" type="button" class="btn btn-pr ...