开发者

Get previous sibling until class is "something"

开发者 https://www.devze.com 2023-04-03 14:21 出处:网络
If I have a long list of <li> elements, when one is clicked, how can I get all sibling elements until one with a class name that contains a given string is reached?

If I have a long list of <li> elements, when one is clicked, how can I get all sibling elements until one with a class name that contains a given string is reached?

Example:

<li>test</li>
<li class="one-two red">test</li>
<li class="green">test</li>
<li>test</li>
&开发者_JAVA百科lt;li>test</li>
<li class="test">test</li>
<li>test</li>
<li>test</li>

In the example above, if li.test is clicked and the given string is ne-tw, would result in all elements in between including the clicked element (andSelf()) and the one-two class element.

Thank you.


jquery has a method for this:

var someclass = "one-two";
$("li").click(function(){
    var sel = $(this).prevUntil("." + someclass).andSelf();
    sel = sel.add(sel.eq(0).prev());
    console.log(sel);
});

http://api.jquery.com/prevUntil

Edit: code sample from comment:

var someclass = "one";
$("li").click(function(){
    var sel = $(this).prevUntil("[class*=" + someclass + "]").andSelf();
    sel = sel.add(sel.eq(0).prev());
    console.log(sel);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消