Reputation: 83
So I know that using "a:first" will get the first link of a page. Lets assume we have the following:
<div class="masterclass">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
</div>
<div class="masterclass">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
</div>
Naturally I can use the following code to get the first "a" of the class "masterclass"
$('.masterclass a:first').click(function() {
alert('yayfirstlink');
});
However I do not understand how to get the first link of every "masterclass"
Upvotes: 0
Views: 71
Reputation: 204
I would recommend using the first of type selector for this.
$('.masterclass a:first-of-type')
This way it will always select the first anchor tag in each masterclass
div even if you put other things in the div later.
http://api.jquery.com/first-of-type-selector/
Upvotes: 0
Reputation: 2413
This is how u loop through each of the masterclass and get the first link of it. i don't know what you want to do with it though so i can only provide this
$(document).ready(function(){
var fields = $('.masterclass a:first-child');
$.each(fields, function(index, val){
alert(index);
});
});
this alerts the current links array index http://jsfiddle.net/kBd82/6/
Upvotes: 1
Reputation: 189
$(".masterclass a:first-child")
is what you are looking for.
so:
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
Upvotes: 1
Reputation: 5222
Try this,
var oFirstAnchor = $(".masterclass a:first-child");
Upvotes: 1
Reputation: 388316
You need to use find() here because your selector will find all the anchor elements with in .masterclass
then filter only the very first one. But when you use .find()
, it will find all the .masterclass
elements first then will find the first anchor element in each of them.
$('.masterclass').find('a:first').click(function() {
alert('yayfirstlink');
});
or if you are sure that the target element will be the first child of its parent then you can use :first-child
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
Upvotes: 2