javascripthtmlcssdom

JavaScript / CSS / DOM - dynamic class value overwrite, concatenation problem/challenge


In this snippet, changing the background-color to yellow works. But when i try to modify the value of 'grid-template-column', which takes an unusual value, a string of repeating 'auto' strings - no go. I'm trying to change the value to ... 'auto auto auto', but it won't overwrite the original value inside the style sheet, which looks like this.. 'grid-template-columns: auto auto auto auto auto auto;' I know this looks very goofy, but if you check out the css param 'grid-template-column', the value it requires is a string of space delineated 'auto's to define the number of columns. A very weird hanging chad that for some reason i can't overwrite.

Thanks in advance.

       // create a reference to linked stylesheet
        const stylesheet = document.styleSheets[0];
        const rules = stylesheet.cssRules || stylesheet.rules; 
        
        // loop through the style sheet reference to find the classes to be modified and modify them

        for (let i = 0; i < rules.length; i++) {
            if (rules[i].selectorText === '.grid-container') {
                rules[i].style['background-color'] ='yellow';
                rules[i].style['grid-template-column'] = 'auto auto auto';
                break;
            }
        }
        

Solution

  • Im not 100% sure but maybe if you change

    rules[i].style['grid-template-column'] = 'auto auto auto';

    to

    rules[i].style['grid-template-columns'] = 'auto auto auto';

    then it might work. The CSS property is grid-template-columns not grid-template-column.