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

javascript - Closest previous element with certain ID (with prev())? - Stack Overflow

programmeradmin7浏览0评论

I have a big div wit a lot of smaller divs within it. Say,

    <div id="parent">
 <div id="child1">
 </div>
 <div id="child1">
 </div>
 <div id="child2">
 </div>
 <div id="child1">
 </div>
 <div id="child1">
 </div>
</div>

If I'm currently at the last 'child1', how dow I get to the top most child1 with prev()? For me it breaks when it reaches 'child2'.

I have a big div wit a lot of smaller divs within it. Say,

    <div id="parent">
 <div id="child1">
 </div>
 <div id="child1">
 </div>
 <div id="child2">
 </div>
 <div id="child1">
 </div>
 <div id="child1">
 </div>
</div>

If I'm currently at the last 'child1', how dow I get to the top most child1 with prev()? For me it breaks when it reaches 'child2'.

Share Improve this question edited Mar 23, 2010 at 6:02 rahul 187k50 gold badges238 silver badges264 bronze badges asked Nov 21, 2009 at 13:50 mathon12mathon12 1814 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

First of all your HTML markup is invalid. There shouldn't be more that one element with the same ID in a document.

Read Element identifiers: the id and class attributes

id:

This attribute assigns a name to an element. This name must be unique in a document.

class:

This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.

You can use the parent and :firstchild to get the first element inside your current parent element.

You can use something like this if you are currently at any child of element 'parent'

$(this).parent().find("div:first-child");

I think you want this:

$(this).prevAll('.child1').eq(0);
 $(this).closest('.parent').find('.child1:first')

I changed to classes, because you really should only ever have one element of any given ID in a page

发布评论

评论列表(0)

  1. 暂无评论