检查元素是否包含数组中的任何类
我有以下几个要素:
以下JS:
var obj = ['nine', 'ten', 'eleven'];
如何检查这些元素中的任何一个是否具有数组中的某个类?
不需要遍历每个元素和每个类来检查它是否存在于元素上。
您可以使用regex
如下:
演示
var arr = ['nine', 'ten', 'eleven']; var classes = '\\b(' + arr.join('|') + ')\\b', regex = new RegExp(classes, 'i'); $('div').each(function() { var elClasses = ' ' + $(this).attr('class').replace(/\s+/, ' ') + ' '; if (regex.test(elClasses)) { $(this).addClass('valid'); } })
div { color: red; } .valid { color: green; }
Invalid Valid Ten Invalid Invalid Valid 11 Valid 9
function checkClasses () { var tagsWithClasses = []; $.each($("div"), function( index, value ){ for (i=0; i
$('div').each(function () { var found = false; var element_classes = $(this)[0].className.split(/\s+/); // Loop each class the element has for (var i = 0; i < element_classes.length; i++) { // Check if each class from the element is within the array of classes we want to match if (['nine', 'ten', 'eleven'].indexOf(element_classes[i]) !== -1) { // We found a match, break out of the loop found = true; break; } } // check if found or not if (found) { // Was found } else { // Was not found } });
var obj = ['nine', 'ten', 'eleven']; var divs =[]; $.each(obj,function(key,value){ var values = value; $(div).each(function(){ var divId = $(this).attr('id'); // Giving some separate id for the div to track it var getClass = $(this).attr('class'); if(getClass.indexOf(values) >= 0) { div.push("divId"); } }); });
您可以遍历元素和结果
如何检查这些元素中的任何一个是否具有数组中的某个类
您必须遍历元素和类,并检查每个元素是否包含数组中的任何类,如下所示
var elements = $('div'); var obj = ['nine', 'ten', 'eleven']; var hasClass = elements.filter(function(index, elem) { return obj.some(function(klass) { return elem.classList.contains(klass); }); }).length > 0;
你可以很容易地把它变成一个函数
function hasClass(elements, classes) { return elements.filter(function(index, elem) { return classes.some(function(klass) { return elem.classList.contains(klass); }); }).length > 0; }
小提琴
使用Array.some
和Element.classList.contains
来避免不必要的迭代和类名的慢匹配。
问题取决于您要做的事情。
如果您尝试创建这些元素的集合,可以从数组中创建一个选择器:
var elemCollection = $( '.' + obj.join(',.') ).doSomething();
也可用于filter()
$existingElementCollection.filter( '.' + obj.join(',.') ).doSomething();
或者可以在is()
var filterSelector = '.' + obj.join(',.'); $someCollection.each(function(){ if($(this).is( filterSelector ){ // do somthing for matches } });
DEMO