如何将类添加到多个元素?

时间:2015-09-15 12:50:56

标签: javascript

基本上我喜欢为具有相同类名的多个元素添加一个新类。目前它只在最后一个类中添加一个类。我尝试过使用document.querySelectorAll但没有得到任何结果。我缺少什么?

HTML示例

<div class="model"></div>
<div class="model"></div>
<div class="model"></div>

JS

 _updateParagraph: function(settings, className) {
    var paragraph = document.querySelector('.' + className);
    paragraph.className = className;
    this._updateParagraphClasslist(settings, paragraph);
  },

全JS

App.Views.Preview = Backbone.View.extend({
  el: "#preview",
  initialize: function() {
    this.listenTo(this.model, "change", this.update);
  },
  update: function() {
    var

      layout = [this.model.get("model")],
      format   = [this.model.get("size"), this.model.get("color-outside"), this.model.get("color")],
      color    = [this.model.get("color-inside")],
      material = [this.model.get('material')],
      lamination = [this.model.get('lamination')],
      logo = [this.model.get('embossing')];

    this._updateParagraph(layout, 'layout');
    this._updateParagraph(format, 'front');
    this._updateParagraph(format, 'back');
    this._updateParagraph(lamination, 'kit-front');
    this._updateParagraph(lamination, 'kit-back');
    this._updateParagraph(logo, 'embossing');
    this._updateParagraph(color, 'colorinner');
    this._updateParagraph(color, 'model');


  },
  _updateParagraph: function(settings, className) {
    var paragraph = document.querySelector('.' + className);
    paragraph.className = className;
    this._updateParagraphClasslist(settings, paragraph);
  },
  _updateParagraphClasslist: function(settings, paragraph) {
    _.each(settings, function(setting) {
      if (_.has(setting, "visual")) {
        paragraph.classList.add(setting.visual);
      }
    });
  }
});

1 个答案:

答案 0 :(得分:12)

  

我想为具有相同类名

的多个元素添加一个新类

使用jQuery,您可以使用类模型和.addClass()来定位所有元素,以便为所有元素添加类:

$('.model').addClass('newclass')

纯粹的JavaScript解决方案可能如下:

var divs = document.querySelectorAll('.model');
for (var i = 0; i < divs.length; i++) {
    divs[i].classList.add('newclass');
}