2

I currently have the following set up for my jQuery request, which is meant to find an element on the page with the id "myid" and apply new CSS rules to it. These rules are not known beforehand, and so I first read a file and store the results in a string array, with the even indexes being the rules and the odd indexes being the values. However, jQuery refuses to let this work. I've trawled over the documentation to no avail, and all I get is that apparently words[0] is of type string[], not string (which shouldn't be the case).

Can I get some advice on this? Here is an example of what I mean:

var words = ["color", "blue", "font-size", "100"]; // these have been parsed from a file and formatted

$("#myid").css({words[0] : words [1], words[2], words[3]}); // This won't apply
Jenna
  • 97
  • 7

4 Answers4

2

I think this code will help you. I tested it on this page only. :)


var words = ["color", "blue", "font-size", "100"];

for (var i = 0; i < words.length; i += 2){
  $("#mainbar").css(words[i], words[i+1]);
}

This loop will help you add any number of rules since you're reading them dynamically.

IamAshKS
  • 749
  • 4
  • 14
2

One way to do this is to build the css object first and pass it in to the jQuery function:

let words = ["color", "blue", "font-size", "100"]; // these have been parsed from a file and formatted

const cssObj = {};
words.forEach((el,idx,arr) => {
   if(!(idx % 2) && (idx + 2 <= arr.length) ){
     cssObj[el] = arr[idx + 1] 
   }
});

$("#myid").css(cssObj); // This won't apply
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myid">MyId Div</div>
symlink
  • 11,984
  • 7
  • 29
  • 50
2

Here is a way to combine the CSS into one object to apply it all at once:

const words = ["color", "blue", "font-size", "100px"];


let cssObj = {};

for (var i = 0; i < words.length; i++){
    cssObj = { ...cssObj, [words[i]]: words[i+1] }
}

$("#mainbar").css(cssObj);

JSFIDDLE

Amir5000
  • 1,718
  • 15
  • 19
1

While you've already accepted an answer, I thought I'd offer an alternative, with explanations in order that you – and future visitors – might learn how the solution works:

// your original, parsed Array:
let words = ["color", "blue", "font-size", "100px"],

// we convert your array of words into a two-dimensional Array
// word-pairs, using Array.prototype.reduce():
// (Please note this approach was taken from user
// Vbyec's answer: https://stackoverflow.com/a/44996257/82548)
  pairs = words.reduce(function(result, value, index, array) {

    // if the index modulo 2 (the remainder of the index divided by 2)
    // is equal to 0:
    if (index % 2 === 0)

      // we push the sliced Array elements - taken from the copy
      // of the Array - into the result Array (the empty Array
      // passed as an argument):
      result.push(
        // here we define the start of the slice as the index
        // of the current Array-element and the end of the
        // slice before the element found at the index of
        // index of the current Array-element + 2:
        array.slice(index, index + 2)
      );
    // we then return the result:
    return result;
  }, []),
// we use Object.fromEntries() to create a new Object from
// the two-dimensional Array we created:
  cssObj = Object.fromEntries(pairs);

// we pass the created-Object to jQuery's css() method:
$('#myid').css(cssObj);

let words = ["color", "blue", "font-size", "100px"], // these have been parsed from a file and formatted
  pairs = words.reduce(function(result, value, index, array) {
    if (index % 2 === 0) {
      result.push(array.slice(index, index + 2));
    }
    return result;
  }, []),
  cssObj = Object.fromEntries(pairs);

$('#myid').css(cssObj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="myid">Some arbitrary text</div>

JS Fiddle demo.

References:

Bibliography:

David Thomas
  • 249,100
  • 51
  • 377
  • 410