Can this 2-liner jquery be shortened to 1 line?
I have these divs, each have the same class .onediv
and distinct ids div1, div2, div3
<div class="alldivs">
<div class="onediv" id="div1">
</div>
<div class="onediv" id="div2">
</div>
<div class="onediv" id="div3">
</div>
</div>
I want to use jquery to change their css display
property so that all of them are display none
except id=div2
which is display block
. Right now I'm doing it this way with 2 lines. Is there a quicker way to do the same thing with one line only?
$('.onediv').css('display', 'no开发者_StackOverflowne');
$('#div2').css('display', 'block');
If you're hiding/showing amongst siblings then the most generic (and still performant) solution is to use .siblings()
, like this:
$("#div2").show().siblings().hide();
Note that .show()
and .hide()
are shortcuts for setting the display
CSS property like you want here (between none
and what it was before, block
in the default <div>
case).
$('.onediv:not(#div2)').css('display', 'none');
it is possible using filter
function, but not recommended for performance reason:
$('.onediv').hide().filter('#div2').show();
$('#div2').siblings().css('display', 'none');
Try this:
$('.onediv').not('.onediv:last-child').css('display', 'none');
Please don't downrank! this works. check here: http://jsfiddle.net/ASBcg/
EDIT: If you want explicitly show that div this would be better:
$('.onediv').css('display', 'block').not('.onediv:last-child').css('display', 'none');
Here is a creative one (but not necessarily useful):
$(".alldivs > div:even").hide();
Here is another one:
$(".onediv:not(:eq(1))").hide();
This code expects that by default your divs are not hidden (ie. no display:none in your css)
精彩评论