如何仅使用jQuery选择top <li> </li>

时间:2012-10-24 13:43:43

标签: jquery

这是一个HTML。我不在乎它是否有效,我只是想使用jQuery从它中查询“title to select”,仅此而已。

<div class="my class1213">
    <h3> just title, no selection</h3>
    <ul>
        <li>title to select</li>
        <li>title to select
            <ul>
                <li>nonono</li>
            </ul>
        </li>
        <li>title to select
           <ul>
             <li>
                 <ul>
                     <li>no selection</li>
                 </ul>
             </li>                 
          </ul>     
        </li>    
    </ul>    

</div>​​​​

我该怎么做?

3 个答案:

答案 0 :(得分:7)

$('.my ul li:first');

应该够了

备选方案:

$('.my ul li:eq(0)');

$('.my ul li:nth-child(1)');

根据undefined的评论进行编辑:

你可以使用他的解决方案,或类似的东西:

$('.my ul li').filter(function(){
    return $(this).text === 'title to select';
});

答案 1 :(得分:2)

您可以使用CSS选择器,也可以使用jQuery traversing函数。

选项a:

$('.class1213 ul li:first-child')
// selects only the first li child of ul

选项b:

$('.class1213 ul li').first()
// first selects all li's, then only uses the first element found

答案 2 :(得分:1)

$('div.my > ul > li:first-child');
相关问题