简体   繁体   中英

Select ul with odd li's

For a dynamic website I'm trying to create a list of items, where the last li (if odd) is 100% wide.

I got this working, the problem I have is that the next UL , also does it, while the last li isn't odd.

Basically: If the last LI in the list is odd, then make 100%.

I'm having an hard time trying to explain myself, so hopefully my fiddle makes more sense:

var target = $( "ul.odd-list > li:last-child");
if ( target.is(":nth-child(odd)"  ) ) { 
    target.css( "width", "98%");
}

demo

Thanks in advance!

ps, I know that i can remove the class from the second ul . But that one has to be there in case the decide to add more li 's.

You need to test each one separately as is will return true if any one of the matching elements meets the condition:

JSFIddle: http://jsfiddle.net/TrueBlueAussie/Ln5uf9y1/5/

var target = $("ul.odd-list > li:last-child");
target.each(function () {
    if ($(this).is(":nth-child(odd)")) {
        $(this).css("width", "98%");
    }
});

Which you can reduce to a single selector:

$("ul.odd-list > li:last-child:nth-child(odd)").css("width", "98%");

JSFiddle: http://jsfiddle.net/TrueBlueAussie/Ln5uf9y1/7/

Well your default width looks like to be 48% width. Lets keep it like it and apply 98% width where needed.

in css :

li {
   width : 48%;
 }
li:last-child:nth-child(odd) {
   width: 98%;
}

if you really want to use jquery to set last width :

$('ul.odd-list > li:last-child:nth-child(odd)').css('width', '98%')

note : TrueBlueAussie answer is right too but I don't like using 'if' where there is no need of it.

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