Ok, I have a series of Unordered Lists on a page I am working on. The list items of each unordered list have a class name for use with some click events that I have done. Now I am trying to find the :first/first() element of a given class name. Problem is, :first/first() return undefined. I know first() you can't specify a selector other than the element type (yet), and when I try
$('.selectorname :first').attr('rel');
to get the rel value of that first one i still get undefined. So I'm a bit confused how to tackle this as its not working the way I had hoped.
EDIT The HTML as per request:
<ul>
<li class="selectorname" rel="something">Some Fun stuff..</li>
<li class="selectorname" rel="something">Some Fun stuff..</li>
<li class="selectorname" rel="something">Some Fun stuff..</li>
<li class="selectorname" rel="something">Some Fun stuff..</li>
<li class="selectorname" rel="something">Some Fun stuff..</li>
</ul>
Ok, I have a series of Unordered Lists on a page I am working on. The list items of each unordered list have a class name for use with some click events that I have done. Now I am trying to find the :first/first() element of a given class name. Problem is, :first/first() return undefined. I know first() you can't specify a selector other than the element type (yet), and when I try
$('.selectorname :first').attr('rel');
to get the rel value of that first one i still get undefined. So I'm a bit confused how to tackle this as its not working the way I had hoped.
EDIT The HTML as per request:
<ul>
<li class="selectorname" rel="something">Some Fun stuff..</li>
<li class="selectorname" rel="something">Some Fun stuff..</li>
<li class="selectorname" rel="something">Some Fun stuff..</li>
<li class="selectorname" rel="something">Some Fun stuff..</li>
<li class="selectorname" rel="something">Some Fun stuff..</li>
</ul>
Share
Improve this question
edited Dec 26, 2017 at 3:48
Brock Adams
93.7k23 gold badges241 silver badges305 bronze badges
asked Mar 1, 2012 at 4:45
chrischris
37k53 gold badges147 silver badges256 bronze badges
0
3 Answers
Reset to default 7$('.selectorname:first').attr('rel');
No space.
You can use :eq selector like; var val = $('.selectorname:eq(0)').attr('rel');
This will select first element from all elements which has "selectorname" class. You can select second element by writing parameter 1 or third element by write 2. Since you have 5 elements has class "selectorname" you can use :eq(0) to select first one of it here.
here: http://jsfiddle/6QxNb/3/
Justice's answer showed you the problem with ":first"
, but since you mentioned the .first()
method this is how you'd use it:
$(".selectorname").first().attr("rel")