LoginSignup
9
5

More than 5 years have passed since last update.

jsでstyleをまとめてセットする(jqueryのcss()風に)

Last updated at Posted at 2017-11-30

コメント頂いた、Object.assign()メソッド利用した書き方が凄くシンプルです!

jqueryと違ってベンダープレフィックスつかないので、
そこらへんが問題ないケースでのみ使用しています。

// function
const css = (elements, object) => {
  for (let i = 0; i < elements.length; i++) {
    for (let value in object) {
      elements[i].style[value] = object[value];
    }
  }
}

// 使い方
const target = document.querySelectorAll('.target');

css(target, {
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  width: '100px',
  height: '100px',
  backgroundColor: 'hsla(50, 100%, 50%, 1)'
});

codepenサンプル

9
5
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5