Добавление и применение своего стиля к элементу

Господа знатоки, помогите разобраться. На странице есть элемент:

<div id="list" class="res"></div>

Необходимо добавить к нему свой класс с помощью JS, вот код:

var styleElement = document.getElementById('list');
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.innerHTML = '.res2 { position:absolute; width:264px; height: 300px; overflow:auto; }';
    document.getElementById('list').appendChild(styleElement);
    document.getElementById('list').className = 'res2';

Скрипт отрабатывает, все создается и применяется, но по факту, визуально изменений не происходит. Если не добавлять новый класс, а заменить существующий вот так:

 var styleElement = document.getElementById('list');
        styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        styleElement.innerHTML = '.res { position:absolute; width:264px; height: 300px; overflow:auto; }';      
document.getElementById('list').appendChild(styleElement);
       

то все норм работает, но так как "res" используется еще и в других элементах, то такое решение не подходит. Как добавить свой класс правильно?


Ответы (1 шт):

Автор решения: Михаил Камахин

const list = document.querySelector('#list');
list.classList.add('inline-block');
list.classList.add('padding-10px');
list.classList.add('color-white');
list.classList.add('background-color-blue');
body {
  font-family: sans-serif;
}

.inline-block {
  display: inline-block;
}

.padding-10px {
  padding: 10px;
}

.color-white {
  color: white;
}

.background-color-blue {
  background-color: blue;
}
<div id="list" class="res">Контент</div>

Можно добавлять стили через JS (но нужно-ли?):

function addStyleSheetFromClasses(classes) {
  const sheet = createStyleSheet();
  classes.forEach(classItem => {
    for (propertyObj of classItem.properties) {

      for (property in propertyObj) {
        const cssText = `${property}: ${propertyObj[property]}`;
        sheet.addRule(`.${classItem.name}`, cssText);
      }

    }
  });
}

function createStyleSheet(href) {
  if (typeof document.createStyleSheet === 'undefined') {
    const createStyleSheetLocal = (href) => {
      function createStyleSheet(href) {
        if (typeof href !== 'undefined') {
          var element = document.createElement('link');
          element.type = 'text/css';
          element.rel = 'stylesheet';
          element.href = href;
        } else {
          var element = document.createElement('style');
          element.type = 'text/css';
        }

        document.getElementsByTagName('head')[0].appendChild(element);
        var sheet = document.styleSheets[document.styleSheets.length - 1];

        if (typeof sheet.addRule === 'undefined')
          sheet.addRule = addRule;

        if (typeof sheet.removeRule === 'undefined')
          sheet.removeRule = sheet.deleteRule;

        return sheet;
      }

      function addRule(selectorText, cssText, index) {
        if (typeof index === 'undefined')
          index = this.cssRules.length;

        this.insertRule(selectorText + ' {' + cssText + '}', index);
      }

      return createStyleSheet(href);
    };
    return createStyleSheetLocal(href);
  }
}

const classes = [{
  name: 'inline-block',
  properties: [{
    'display': 'inline-block'
  }]
}, {
  name: 'padding-10px',
  properties: [{
    'padding': '10px'
  }]
}, {
  name: 'color-white',
  properties: [{
    'color': 'white',
  }]
}, {
  name: 'background-color-blue',
  properties: [{
    'background-color': 'blue',
  }]
}];

addStyleSheetFromClasses(classes);
const classesName = classes.map(item => item.name);
const list = document.querySelector('#list');
list.classList.add(...classesName);
<div id="list" class="res">Контент</div>

→ Ссылка