2015-09-15 70 views
2

基本上我喜歡用同一個類名向多個元素添加一個新類。目前它只爲最後一個類添加一個類。我曾嘗試使用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); 
    }, 

FULL 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

使用'addclass'。 –

+1

爲什麼原生js DOM函數和'jQuery'標籤? ^^ – moonwave99

+0

@AmeyDeshpande http://jsfiddle.net/infous/8woaegx2/這可能是你想要的代碼的一個明確的例子。檢查DOM中的結果。 – starikovs

回答

8

我喜歡新的類添加到多個元素具有相同的類名

使用jQuery,您可以針對與.addClass()一起級車型的所有元素添加類所有的人:

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

純JavaScript解決方案可能如下:

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

不是我。也許他正在尋找純粹的js版本。 –

+2

標籤說的是jQuery。看起來很對我! – JonWells

+0

@CrimsonChin它在哪裏? – Jai

相關問題