最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get the `rel` attribute value of the first element with class xxxxx - Stack Overflow

programmeradmin1浏览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>

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
Add a ment  | 

3 Answers 3

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")
发布评论

评论列表(0)

  1. 暂无评论