Try this:
$(this).attr('class').substring(0,7)="bgcolor"
And for getting the attributes of a class I wanna show you this:
Question
Sorry if this is a 'noob' question. (I've heavily edited it to be clearer as to what I was looking for.) Consider some links:
<p><a class="bgColor_0" href="whatever">Click Me</a></p>
<p><a class="bgColor_1" href="whatever">Click Me</a></p>
<p><a class="bgColor_2" href="whatever">Click Me</a></p>
Somewhere else on the page there is a DIV which also uses the same class name. So in the stylesheet:
div.bgColor_1 {background-color: #ffffff; }
div.bgColor_2 {background-color: #00ffff; }
div.bgColor_3 {background-color: #ffff00; }
What I want is to get the value of the background-color property of the class of the clicked as a string (or a null if not set).
So I want to create a click function which tests for a class beginning with bgColor_
jQuery('a').click( function(){
myClass = jQuery(this).attr('class').match(/\bbgColor_\S+/g);
// eg. myClass = 'bgColor_0';
// now... how do I get the background-color property of bgColor_0?;
} );
What I want to get to is the -value- of the backgroundColor property of the div with the class myClass
eg. If the user clicked a.bgColor_1, I want to obtain the background-color property of the class div.bgColor_1 in the stylesheet and then assign another (to be determined) div to class bgColor_1 so I can change its colour.
Solution
Try this:
$(this).attr('class').substring(0,7)="bgcolor"
And for getting the attributes of a class I wanna show you this:
OTHER TIPS
You're looking for the partial match selector:
$(this).is("[class^='bgColor']")
It's short and sweet, it requires that the class starts with bbgColor
like your examples.
If you need to allow for the class to appear anywhere in the attribute, use:
$(this).is("[class*='bgColor']")
I think people are answering the wrong question. I think your question was
"How do I get the background-color property of bgColor_0?" but it should have been "How do I get the background-color property of links that have a css class starting with bgColor?"
http://jsfiddle.net/mendesjuan/j4q56/
jQuery('a').click( function(){
var $link = jQuery(this);
var isMatch = $link.attr('class').match(/\bbgColor_\S+/g);
if (isMatch) {
console.log($link.css('background-color'));
}
} );
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match and http://api.jquery.com/css/
Note that this pattern of bgColor_0
bgColor_1
seems like an anti pattern and is code smell.
You mean like this?
jQuery('a').click( function(){
alert( $(this).css('background-color') );
} );