0

My way of doing this hasn't worked for me yet because every time I try and set the variable to the element, it just makes elem.style.property equal to value. var elem = document.getElementById('cssTest'); is the element, and elem.style.backgroundColor = value; is what I am setting equal to. You would think that the value would just apply, even if backgroundColor was the value of another variable, but no, it just makes the entire thing equal value. So if value equals a hexadecimal value, it sets elem.style.property to that value, literally. The CSS doesn't update to fit the value and then it just fails. That would be my way of telling you to fix it, but I can't get it to work myself. Anyone know how to set it using the below code?

var elem = document.getElementById('cssTest');
var property = 'backgroundColor';
var value = '#ffffff';

elem.style.property = value;

That just doesn't work. It might be because property is a string, but I don't know how to convert it. Do I just get rid of the quotes around the assignment value? I do have a function going through a JSON array to find the property first, but I don't know how to have it come out as an object. I will put a sample below. Please let me know what to fix!

var cssProps = [
    {"prop":"background-color","jsprop":"backgroundColor"},
    {"prop":"margin-top","jsprop":"marginTop"},
    {"prop":"padding-bottom","jsprop":"paddingBottom"}
];
function parseCSS(property,array) {
    for (var i = 0;i < array.length;i++) {
        if(property == array[i].prop) {
            return array[i].jsprop;
        };
    }
}
var output = parseCSS('background-color',cssProps);
console.log(output);
SubLock69
  • 91
  • 1
  • 7
  • 1
    You're looking for this: `elem.style[property] = value;` –  Oct 13 '16 at 02:15
  • That seemed to work, but there is an error of "Cannot read property 'style' of null". I may have input the code wrong, but the values for each parameter stays the same, just doesn't seem to be applying it – SubLock69 Oct 13 '16 at 02:49
  • Actually, I am building a code library for my club at school, and I just didn't know how to change CSS attributes using variables. THANK YOU SO MUCH!!!! That has solved many of my issues and now it works! The one that didn't work was another version of the CSS parser that found the hyphens and deleted them then capitalized the next letter, but the code for it was faulty. I am just using the JSON array sorter code instead and it works like a charm! Thanks again! – SubLock69 Oct 13 '16 at 12:38
  • You're very welcome :) This solution was also mentioned in the question yours was marked as being a duplicate of though :) –  Oct 13 '16 at 16:10

0 Answers0