0

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>
0

3 Answers 3

7
$('.selectorname:first').attr('rel');

No space.

0
2

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.net/6QxNb/3/

1
  • Justice Erolin, nailed it. when I accidentally left a space in the syntax and simply missed it in my review trying to figure it out.
    – chris
    Mar 1, 2012 at 4:54
0

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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.