开发者

jQuery selector for "all not first in a div preceded by a object with class"

Here is a sample of what I have in 开发者_如何转开发HTML:

<span class="a">Test</span>
<div class="b">
  <div id="x_ABC">ABC must NOT be hidden</div>
  <div id="x_DEF">DEF must be hidden</div>
  <div id="x_GHI">GHI must be hidden</div>
  <div id="JKL">JKL must NOT be hidden</div>
</div>

All I want is to hide with jQuery all the divs with an id starting with "x" inside the div with class "b" preceded by a html tag with a class "a".

I tried this code :

$('.a + div.b div[id^=x]:gt(0)').hide()

But it doesn't do what I want. Does anyone know how to fix the selector using only the class "a", "b" and "id^=x"?

Thank you!


Quotes in attribute selectors are mandatory:

$('.a + div.b div[id^="x"]:gt(0)').hide()

DEMO

For performance reasons, you might want to use .slice():

$('.a + div.b div[id^="x"]').slice(1).hide()


You need quotes around the x: http://api.jquery.com/attribute-starts-with-selector/


Just a more functional alternative:

$('div.b').each(function(_, b) {
    var $b = $(b);

    if( $b.prev().hasClass('a') ) {
        $b.children().slice(1).filter(function() { return this.id.charAt(0) === 'x' }).hide();
    }
});


I think it's as simple as this

$('.a + .b > *[id^="x"]:nth-child(n+2)').hide();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜