简体   繁体   中英

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', 'none');    
$('#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');

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)

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');    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM