I have a div with few classes in no specific order.
<div class="whatever styledark myclass"></div>
I'm interested in the styledark class. This can be styledark, stylewhite, stylered.... I want to get this class name no matter what color comes after the word style. The question is, when i click on the div, how i do i alert this class name that start with the word style disregarding other classes in the div. The classes are in no specific order.
In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
This is a great question. Although it can be done using many of the answers mentioned here, this is a little awkward and costly performance wise. The way i would recommend you do it is put the style class last, that way with only one line of code you can output the class name you are after.
$('element').attr('class').split(' ').pop();
$('div').click(function() {
var style = this.className.split(/\s/).filter(function( cn ) {
return cn.indexOf('style') === 0;
});
alert(style);
});
Note this code uses Array.prototype.filter
and .indexof()
, which is not available in old'ish browsers. To make this more generic, it would look like:
$('div').click(function() {
var name = '';
$.each(this.className.split(/\s/), function( _, cn ) {
if( cn.indexOf('style') === 0 ) { name = cn; return false; }
});
alert(name);
});
I used to use the classList attribute, but unfortunately it seems that it's not in safari. :( The following is what I came up with, but the RegExp may need just a little tweaking.
$('div.button').each(function() {
$m = this.className.match(/(^|\s)style\S+(\s|$)/);
if($m) {
$(this).bind('click', { colorName : $m[0] }, function(e) {
alert(e.data.colorName);
);
}
});
$('div').click(function(){
var c = $(this).attr('class').split(/\s+/);
for(var s in c)
if(c[s].indexOf('style') == 0)
alert(c[s]);
});
live example : http://jsfiddle.net/gion_13/rXkNy/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With