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

Ale*_*ein 5 javascript

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

HTML示例

<div class="model"></div>
<div class="model"></div>
<div class="model"></div>
Run Code Online (Sandbox Code Playgroud)

JS

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

全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);
      }
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

Mil*_*war 15

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

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

$('.model').addClass('newclass')
Run Code Online (Sandbox Code Playgroud)

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

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

  • 标签说是jQuery.看起来对我来说! (2认同)
  • 感谢您提供原始 js 版本......很少有人提供原始 js 解决方案......;)+1。 (2认同)

con*_*exo 6

在 2022 年(不考虑 IE),您将执行以下操作(使用querySelectorAllforEach和箭头函数):

document.querySelectorAll('.foo').forEach(el=>el.classList.add('bar'));
Run Code Online (Sandbox Code Playgroud)