Reputation: 469
I have 3 anchors with 3 divs The anchors are like that:
<a class="home sharedClass">home</a>
<a class="about sharedClass">about</a>
<a class="contact sharedClass">contact</a>
When I click one of them I get the contents of the corresponding div which its id is the same as the first class (home, about or contact)
I have a little jQuery code that has to select the right class But the result is an alert telling the name of theClass:
$('a.sharedClass').click(function(){
var theClass = $(this).attr('class[0]');
alert(theClass)
});
The problem is that this function returns "undefined". How to fix this?
Thanks.
Upvotes: 2
Views: 1891
Reputation: 116100
That's because the attribute class
is just a string. When you get it, you will get all classes in that one string value.
If you want to get items, you can explode it to an array and then access item 0.
theClass = $(this).attr('class').split(' ', 1)[0];
In more modern browsers (about all relevant browsers actually), you can use the classList property of an element to get the list of classes and add to it. I'm not sure if that will return the classes in a particular order, though. I think in implementation it's more a 'bag' than a 'list, because you can check if a class is in it, but not get or modify, say, the first item.
In the end, that's the safest way to use classes anyway. After all, you'd want to check if an element has a class, not if it's the first class per se.
Upvotes: 3
Reputation: 17640
why not just get the text then you don't even need the class
$('a.sharedClass').click(function(){
alert(this.text)
});
Upvotes: 0
Reputation: 8376
The class
attribute is not an array. It is a string, as are all attributes. Further, the attr
function will be looking for an attribute on the element named class[0]
which it will not find.
$('a.sharedClass').click(function(){
var theClass = $(this).attr('class'),
firstClass = (theClass || '').split(' ')[0]; // handle if no class attribute
alert(firstClass);
});
Upvotes: 1
Reputation: 4820
Get the class attribute first.
var theClass= $(this).attr('class');
You'll have to break (explode/split) it
var split = theClass.split(' '); // this returns an array
Finally you could access the first class
var firstClass = split[0];
Upvotes: 5