I have got some classes
.text-1
.text-2
.text-3
I want to select them all, how to do that? Thanks for the help
$('#qvDetails,#qvAdd,.qvFramedActive,#qvMoreSizes').live('mouseover',function(){
$(this).addClass('qvHover');
});
example from one of my projects.you can mention both divs and classes together like above
you can provide as coma separated class or divs in the same...
Here's a function that deals with the issue of multiple classes, in cases like <div class="foo bar barfood">
:
function classStartsWith(str) {
return $('div').map( function(i,e) {
var classes = e.className.split(' ');
for (var i=0, j=classes.length; i < j; i++) {
if (classes[i].substr(0, str.length) == str) return e;
}
}).get();
}
The function returns an array of matching DOM elements. You can use it thus:
$( classStartsWith('text-') ).doSomething();
Here's an example: http://www.jsfiddle.net/Ms6ey/3/
Of course this assumes the selector 'div'
. The question seems to be asking about any element at all. It's easy enough to make the function take a selector as another argument, and use that in place of the hardcoded one in the example.
Here's an attempt at a solution that's both accurate and not too slow:
var elts = $('*[class*="text-"]')
.filter(function () {
return this.className.match(/(?:^|\s)text-/);
});
Which works by using the (hopefully) fast Sizzle code to find elements that have "text-" anywhere in their class
attribute, and then calls a function on each of those to filter them down to the ones that actually have "text-" at the beginning of a class name.
Try this. For more details refer jquery selectors
$('*[class^="text"]')
You don't necessarily need to specify asterisk *
, you can do this too:
$('[class^="text-"]')
Notice the addition of -
after text
something you are looking for.
Check out the jQuery starts with selector for more information.
You can do this with just two selectors in one function call:
$('[class^="text-"], [class*=" text-"]')
This will check if the class attribute starts with text-
or if there is any part of the class string that has a space followed by text-
. This solves any issues you might have with the
$('[class^="text-"], [class*=" text-"]')
.css('background-color', '#00FF00'); // add background color for demo
/* just for demo */
div:after {
content: "class: " attr(class);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text-1 test"></div>
<div class="text some-text-1"></div>
<div class="nope text-long-class-name"></div>
<div class="some-text-1"></div>
<div class="even get text-n-here"></div>
You could pull this out into a function that selects all elements with a class that matches a given prefix, as well:
function selectElementsWithClassPrefix(prefix) {
return $('[class^="' + prefix + '"], [class*=" ' + prefix + '"]');
}