I have the following elements:
<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight ten"></div>
<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight eleven"></div>
<div class="one two three four five six seven eight nine"></div>
And the following JS:
var obj = ['nine', 'ten', 'eleven'];
How do I check if any of these elements has one of the classes in the array?
I have the following elements:
<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight ten"></div>
<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight"></div>
<div class="one two three four five six seven eight eleven"></div>
<div class="one two three four five six seven eight nine"></div>
And the following JS:
var obj = ['nine', 'ten', 'eleven'];
How do I check if any of these elements has one of the classes in the array?
Share Improve this question edited Jul 13, 2015 at 14:38 Tushar 87.3k21 gold badges163 silver badges181 bronze badges asked Jul 13, 2015 at 14:05 gespinhagespinha 8,50717 gold badges59 silver badges96 bronze badges 4-
Cartesian Check! Woah!
:P
– Praveen Kumar Purushothaman Commented Jul 13, 2015 at 14:06 - What do you mean by "check"? Do you just want to select all the divs that contains a class in your array? – alan0xd7 Commented Jul 13, 2015 at 14:06
- If you really mean check then api.jquery./hasclass will be used somewhere – Huangism Commented Jul 13, 2015 at 14:07
- like that? JsFiddle – Jean-philippe Emond Commented Jul 13, 2015 at 14:13
6 Answers
Reset to default 7No need of loop over each of the element and each of the class to check it it exists on the element.
You can use regex
as follow:
Demo
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;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="one two three four five six seven eight">Invalid</div>
<div class="one two three four five six seven eight ten">Valid Ten</div>
<div class="one two three four five six seven eight">Invalid</div>
<div class="one two three four five six seven eight">Invalid</div>
<div class="one two three four five six seven eight eleven">Valid 11</div>
<div class="one two three four five six seven eight nine">Valid 9</div>
REGEX EXPLANATION
\b
: Will match the word boundary|
: Works as OR in regexarr.join('|')
: Will join all the elements of array using|
to join()
: Capturing Group. In this case used for matching one of the class
So, regex
in above case will be
/\b(nine|ten|eleven)\b/
function checkClasses () {
var tagsWithClasses = [];
$.each($("div"), function( index, value ){
for (i=0; i<obj.length; i++) {
if ($(value).hasClass(obj[i])) {
tagsWithClasses.push($(value));
continue;
}
}
});
return tagsWithClasses;
}
$('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");
}
});
});
You can loop through the elements and the the result
How do I check if any of these elements has one of the classes in the array
You'd have to iterate over elements and classes, and check if each element contain any of the classes in the array, something like this
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;
You could easily make that into a function
function hasClass(elements, classes) {
return elements.filter(function(index, elem) {
return classes.some(function(klass) {
return elem.classList.contains(klass);
});
}).length > 0;
}
FIDDLE
Using Array.some
and Element.classList.contains
to avoid uneccessary iteration and slow matching of classnames.
Question depends on what you are trying to do.
If you are trying to create a collection of those elements you can create a selector from the array:
var elemCollection = $( '.' + obj.join(',.') ).doSomething();
Can also be used in filter()
$existingElementCollection.filter( '.' + obj.join(',.') ).doSomething();
Or can be used in is()
var filterSelector = '.' + obj.join(',.');
$someCollection.each(function(){
if($(this).is( filterSelector ){
// do somthing for matches
}
});
DEMO