这是与此主题相关的后续问题...... jQuery - Grouping multiple elements with the same class
问题: 感谢上面的代码。如果我在div中有多个类,我怎么能修改这个?例如:
class =" div1 section-1"
class =" div2 section-1"
我仍然需要像示例中那样组合所有节类,但我为每个div都有一个额外的类。
答案 0 :(得分:2)
您的代码如下所示:
$(document).ready(function() {
// Get all the classes
var classes = $('[class*=section]').map(function() {
var section = $.grep(this.className.split(" "), function(v, i) {
return v.indexOf('section-') === 0;
}).join()
return section;
});
// Filter only unique ones
var uniqueClasses = $.unique(classes);
// Now group them
$(uniqueClasses).each(function(i, v) {
$('.' + v).wrapAll('<div class ="parent-' + v + '"></div>');
});
});
div[class*=section] {
background: #fd6548;
margin: 10px;
}
div[class*=parent-section] {
background: #dd5500;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1 section-2">a</div>
<div class="div1 section-1">b</div>
<div class="div2 section-1">c</div>
<div class="div2 section-2">d</div>