从元素数组中获取类的列表

时间:2017-06-05 19:35:16

标签: javascript jquery arrays

我有以下数组,其中包含许多option元素,具体取决于它是否具有hidden类。

var list = $('#condition option').not('.hidden');

如何获得这些元素的类数组?

我尝试过:

var list = $('#condition option').not('.hidden').attr('class');

但是,这只返回与数组中最后一个元素关联的类。

4 个答案:

答案 0 :(得分:3)

您可以使用.map():

$('#condition option').not('.hidden').map(function() {
  return this.className.split(' ');
}).get();

Here's a fiddle

答案 1 :(得分:0)

与评论中建议的一样,使用JQuery的每个函数。

var list_condition = $('#condition option').not('.hidden');
var list_class = []; // Creates an empty array

$(list_condition).each(function(index) {
  list_class.push($(list_condition)[index].attr('class')); // Pushes the element into the array
});

答案 2 :(得分:0)

也许是这样的。该列表选择所有dom元素。 .each遍历它们。

var list = $('#condition option').not('.hidden').attr('class');
$(list).each(function( index ) {
  var myClass = $(this).attr("class"); 
  console.log(myClass);
});

答案 3 :(得分:0)

您可以使用jQuery.each()功能

执行此操作

示例:

var list = $('#condition option').not('.hidden'),
    classes = [];

$(list).each(function () {
  classes.push($(this).attr('class'));
});
    
console.log(classes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="condition">
   <option class="some-class-1" > some option </option>
   <option class="some-class-2" > some option </option>
   <option class="some-class-3" > some option </option>
   <option class="some-class-4" > some option </option>
   <option class="some-class-5" > some option </option>
   <option class="some-class-6" > some option </option>
   <option class="some-class-7" > some option </option>
   <option class="some-class-8" > some option </option>
</select>

<强>更新

如果您要拆分/分隔每个元素,例如某些option有一些类class-1-aclass-1-b等等

在这种情况下,您可能需要String.prototype.split()

示例

var list = $('#condition option').not('.hidden'),
    allClasses = [];

$(list).each(function () {
  var elemClasses = $(this).attr('class');
    elemClasses.trim().split(/\s+/).map(function (x) {
        allClasses.push(x);      
    })
  
});

console.log(allClasses);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="condition">
   <option class="some-class-1-a        some-class-1-b" > some option </option>
   <option class="some-class-2-a some-class-1-b " > some option </option>
   <option class="some-class-3" > some option </option>
   <option class="some-class-4" > some option </option>
   <option class="some-class-5" > some option </option>
   <option class="some-class-6" > some option </option>
   <option class="some-class-7" > some option </option>
   <option class="some-class-8" > some option </option>
</select>