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

13

我想给多个具有相同类名的元素添加一个新的类。但目前它只为最后一个元素添加类。我已尝试使用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
为什么要同时使用本地 JS DOM 函数和 jQuery 标签呢? ^^ - moonwave99
@AmeyDeshpande http://jsfiddle.net/infous/8woaegx2/ 这可能是你想要的代码的一个清晰的例子。在DOM中检查结果。 - starikovs
3个回答

36

我想要给多个具有相同类名的元素添加一个新的类

使用jQuery,你可以选中所有具有类名model的元素,并使用.addClass()为它们都添加一个类:

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

一个纯JavaScript的解决方案可以如下所示:

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

不是我。也许他正在寻找纯JS版本。 - user405398
@CrimsonChin 它在哪里? - Jai
@Jai,遗憾的是,要证明这一点需要时光机,因为用户已经删除了该标签。 - Jon Wells
2
感谢您提供这个原始的JS版本... 很少有人提供原始的JS解决方案... ;) +1. - Lewis

5
在2022年(不考虑IE),你会采用以下方式进行操作(使用querySelectorAllforEach和箭头函数):
document.querySelectorAll('.foo').forEach(el=>el.classList.add('bar'));

一行简洁的解决方案。 - Kinglybird

0

很抱歉来晚了,但我认为使用getElementsByClassName可能更有效率:

var myDivs = document.getElementsByClassName('model');
[].forEach.call(myDivs, function(mySingleDiv) {
    mySingleDiv.classList.add('newclass');
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接